sinonjs

A few days ago I wanted to test a JS function, part of the test was to verify that another function gets called, and gets called correctly (with the correct parameters). I ended up using Sinon for the task, and now looking at it — it’s pretty easy and straightforward. Thing is, when I was trying to write my tests I didn’t find good examples and there was a little struggle until I figured it out, which is the motivation for this post (why not share and make someone’s else life easier, right?).

So let’s get down to business!

Say the function I want to test looks like the following:

const events = require('events');function pleaseTestMe(a, b, c) {
...
events.sendBigDealEvent(a, c, x); // test that it was called!
...
return something;
}

I wanted to leverage Sinon to stub sendBigDealEvent in order to test that it was called properly.

describe('Testing pleaseTestMe()', () => {
let a = 1, b = 2, ...
...

it('Test that sendBigDealEvent() was called correctly', () => {
const sendBigDealEvent = sinon.stub(events, 'sendBigDealEvent');
pleaseTestMe(a, b, c);
sinon.assert.calledOnce(sendBigDealEvent);
sinon.assert.calledWith(sendBigDealEvent,
sinon.match(a, c, sinon.match.any));
sendBigDealEvent.restore();
});
...
});

As we can see, Sinon makes it easy to stub a module’s function using the syntax:

const sendBigDealEvent = sinon.stub(events, 'sendBigDealEvent');

Pay attention that the name of the function is passed as a string as the second argument to stub.

Then, Sinon allows us to check how many times the function was called with cute utility methods such as: calledOnce, calledTwice, calledTrice and callCount.

Further, we can check that sendBigDealEvent was called with specific arguments by using a combination of sinon.assert.calledWith and sinon matchers:

sinon.assert.calledWith(sendBigDealEvent, 
sinon.match(a, c, sinon.match.any));

You can read more about assertions & matchers here.

And last but not less important: when we’re done with the stub we should restore it:

sendBigDealEvent.restore();

The reason for that is that if we’ll try to use sinon to stub that same method in another test and we forgot to restore() we’ll run into an exception saying that we’re trying to wrap an object which is already wrapped, something like:

Attempted to wrap someObj which is already wrapped

Nice & easy, right?

Note: if you‘re considering using Sinon, I recommend that you’ll also read a follow-up post I wrote: Why isn’t my Stub working

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

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