Search code examples
node.jssinon

Sinon stub doesn't seem to work when object destructuring is used


Let's say you have a method called myMethod in the module myModule which is looking like this:

function myMethod() {
   return 5;
}
module.exports.myMethod = myMethod;

Now if I want to stub this method to return 2 instead of 5 with Sinon I would write

const myModule = require('path/myModule');
sinon.stub(myModule, 'myMethod').returns(2);

Now in the place where you actually call the method you happen to import the method like this with object destruction

const { myMethod } = require('path/myModule');
console.log(myMethod()); // Will print 5

If you do that, myMethod is actually not stubbed and won't return 2 but 5 instead.

If you instead require again the module and use the function from the required module it will work

const myModule= require('path/myModule');
console.log(myModule.myMethod()); // Will print 2

Is there anyone who has a solution to this other than just changing the way I import my functions?


Solution

  • The stubbed myMethod will have a different reference than the original method. In the destructuring example, you are setting the reference before it can be stubbed.

    // cannot be stubbed
    const { myMethod } = require('path/myModule');
    
    // can be stubbed
    const myModule = require('path/myModule');
    myModule.myMethod();
    

    Check out this similar question for more details