Javascript: Mocking Constructor using Sinon

I needed a solution for this because my code was calling the new operator. I wanted to mock the object that the new call created.

var MockExample = sinon.stub();
MockExample.prototype.test = sinon.stub().returns("42");
var example = new MockExample();
console.log("example: " + example.test()); // outputs 42

Then I used rewire to inject it into the code that I was testing

rewiredModule = rewire('/path/to/module.js');
rewiredModule.__set__("Example", example);

Use sinon.createStubInstance(MyES6ClassName), then when MyES6ClassName is called with a new keyword, a stub of MyES6ClassName instance will returned.


Using Sinon 4.4.2, I was able to mock an instance method like this:

const testObj = { /* any object */ }
sinon.stub(MyClass.prototype, "myMethod").resolves(testObj)
let myVar = await new MyClass(token).myMethod(arg1, arg2)
// myVar === testObj

A similar solution provided here: Stubbing a class method with Sinon.js


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()