Using Sinon Stubs

DZone 's Guide to

Using Sinon Stubs

Learn how to test your JavaScript code by spies, called stubs, using the Sinon.js library. It's quick and easy, and will make your life easier!

· Web Dev Zone ·
Free Resource

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 back at it, it’s pretty easy and straightforward. The 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 go down to business!

I wanted to leverage Sinon to stub sendBigDealEventin order to test that it was called properly:

const events = require('events');

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

Which I was able to achieve by:

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.calledWith(sendBigDealEvent, sinon.match(a, c, sinon.match.any));    

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 to the fact 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: calledOncecalledTwicecalledTriceand callCount.

Further, we can check that sendBigDealEventwas called with specific arguments by using a combination of sinon.assert.calledWithand Sinon matchers:

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

You can read more about assertions and matchers here.

And las.t but not less: when you’re done with the stub you should release it:


The reason for that is that if you’ll try to use Sinon to stub that same method in another test and if you forget to restore()you’ll run into an exception saying that you’re trying to wrap an object which is already wrapped. Something like:

Attempted to wrap someObj which is already wrapped

Nice and easy, right?

javascript tutorials ,web dev ,testing code

Published at DZone with permission of Nir Alfasi . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}