Suppose I create an object using a constructor:
function MyConstructor() {
this.myMethod = () => console.log('foo');
}
const myObject = new MyConstructor();
And now in my test file I want to stub the myMethod
method. If I had defined myMethod
on the prototype, this would be pretty straightforward. One could just use:
sinon.stub(MyConstructor.prototype, 'myMethod')
But this doesn't work when the method is defined in the constructor using this
, as in the example above.
This is an issue that's hard to avoid because some 3rd-party libraries define instance methods in this way, i.e., within the constructor instead of on the prototype. And we need a way to stub such methods when testing.