0

I have the following scenario, first the class under test, called utils.js:

var exports = module.exports = {};

[...]

var internalHelper = exports.internalHelper = function internalHelper(params) {

    [...]

    return A.library.promise();
}

[...]

var methodUnderTest = exports.methodUnderTest = function methodUnderTest(params) {

    [...]

    internalHelper(theParams)
    .then(result => {

        [...]

    });

    [...]

}

[...]

The relevant test snippet looks like this:

var internalHelperStub = sinon.stub(utils, 'internalHelper');
internalHelperStub.resolves({ any: 'response' });

The problem is that the actual method gets called, not the stub.

There are a couple of very similar questions, not satisfied with the answers though:

Why cannot this be done???

If there is a reason for it, what is the proper structure of the code for a utility class?

I don't see the reason why I should be splitting my code with no need and I do see the reason why this should work.

EDIT: James answered this question here, I am keeping my answer as it provides explanation and code snippet solution. Leaving to SO moderators to mark as duplicate, merge or whatever is done in this cases ;)

1 Answers1

0

I think I figured out a way of solving it.

Essentially, Sinon is able to stub just the references that are exposed from a file / class.

That means that in this scenario below you won't be able to stub the call to B method, because it is invoked using an internal reference, which is not affected by Sinon stubbing:

/*********** Code under test: myCode.js ************/

var exports = module.exports = {};

[...]

var B = exports.B = function B() {

}

[...]

var A = exports.A = function A() {
    B();
}

/*********** Test code: myCode.test.js ************/
[...]
bStub = sinon.stub(myCode, 
bStub.returns...

This ☝️ will result in the real method being invoked during testing, regardless any stubbing...

To get the method stubbed, just use it using the exports reference instead, in the snippet above:

var A = exports.A = function A() {
    exports.B();
}
  • 1
    Was 99% sure this was the issue was but without seeing a test I didn't want to answer - I've [answered](https://stackoverflow.com/questions/47796229/sinon-not-stubbing-on-module-exports/47796465#47796465) a similar question on this previously, perhaps I could've linked earlier which may have saved you some time! – James Dec 09 '18 at 00:47