Why my Stub is not working (Using Sinon Stubs — part II)

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

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 myModule
function 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 myModule
function 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!).


Why my Stub is not working (Using Sinon Stubs — part II) was originally published in Everything Full Stack on Medium, where people are continuing the conversation by highlighting and responding to this story.

Senior Software Engineer

Backend Group

Thank you for your interest!

We will contact you as soon as possible.

Want to Know More?

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com
Thank you for your interest!

We will contact you as soon as possible.

Let's talk

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com