[removed] Mocking Constructor using Sinon

前端 未结 8 2118
迷失自我
迷失自我 2021-02-06 20:47

I am pulling my hair out trying to figure out how to mock a constructor using sinon. I have a function that will create multiple widgets by calling a constructor that accepts a

相关标签:
8条回答
  • 2021-02-06 21:43

    From the official site of sinonjs:

    Replaces object.method with a stub function. The original function can be restored bycalling object.method.restore(); (or stub.restore();). An exception is thrown if the property is not >already a function, to help avoid typos when stubbing methods.

    this simply states that the function for which you want to create the stub must be member of the object object.

    To make things clear; you call

    sinon.stub(window, "MyWidget");
    

    The MyWidget function needs to be within the global scope (since you pass window as parameter). However, as you already said, this function is in a local scope (probably defined within an object literal or a namespace).

    In javascript everyone can have access to the global scope, but not the other way around.

    Check where you declare the MyWidget function and pass container object as first parameter to sinon.stub()

    0 讨论(0)
  • 2021-02-06 21:44

    I used Mockery to Mock a Constructor/Function without any problems.

    var mockery = require('mockery');
    var sinon = require('sinon');
    
    mockery.enable({
      useCleanCache: true,
      warnOnReplace: false,
      warnOnUnregistered: false
    });
    
    exports.Client = function() {/* Client constructor Mock */};
    var ClientSpy = sinon.spy(exports, 'Client');
    mockery.registerMock('Client', ClientSpy);
    
    var Factory = require('Factory'); // this module requires the Client module
    

    You should be able to apply a Sinon Spy just as the example above does.

    Make sure to disable or reset Mockery after the test(s)!

    0 讨论(0)
提交回复
热议问题