Using Sinon Stubs

Jan 26 · 2 min read

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 go down to business!

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

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

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

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:

You can read more about assertions & matchers here.

And last but not less important: 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 you forgot to restore() you’ll run into an exception saying that you’re trying to wrap an object which is already wrapped, something like:

Nice & easy, right?


Written by

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade