Why isn’t my Stub working (Using Sinon Stubs — part II)

Nir Alfasi
Israeli Tech Radar
Published in
2 min readJun 2, 2021

About a year ago I wrote Using Sinon Stubs, if you’re new to Sinon I recommend you read that post first!

sinon is a library that provides test spies, stubs and mocks in JavaScript

It all started when a friend wrote a test but the stub he created wasn’t working: reviewing the test everything seemed to be done properly, yet it was obvious from the test logs that the real method was called instead of the stub.

What was going on? And how can we fix it?

It took a bit of digging to figure out, and the root-cause was not trivial which is why we’re sharing it with you, hoping to save you some pain…

So let’s begin!

A simplified version of the module we were trying to stub:

// inside myModulefunction funcA () {
// do something
}

function funcB () {
const x = funcA();
// do something else
}

exports = {
funcA,
funcB,
};

The test looked something like this:

sinon.stub(myModule, 'funcA').returns({ x: 100 });

So why wasn’t the stub called, and how to fix it?

After some investigation we found the following: the stub replaces references to function in the object which is exported from myModule . The problem is that when funcB calls funcA it calls it directly, not through the exported module functions.

This means that a trivial way to fix it will be to rewrite the module like this:

// inside myModulefunction funcA () {
// do something
};

function funcB () {
const x = exports.funcA(); // use the function through exports
// do something else
};
exports = {
funcA,
funcB,
};

A colleague pointed out that this style looks “ugly”, and I agree… but hey, it works :)

If you can come up with a better way to workaround/fix this problem, please comment and I’ll update this post (and give you credit for it of course!).

--

--

Nir Alfasi
Israeli Tech Radar

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann