/ jest

Migrating from Mocha and Sinon to Jest

Level - Intermediate. Read Time ~ <5 minutes.

Initially when I was building my boilerplate, I used Mocha for unit testing and Sinon for mocking/stubbing. With the growing popularity and benefits of Jest, I decided to migrate away from Mocha. By using Jest I no longer needed Sinon for mocking/stubbing as with Jest this comes out of the box.

If you look at these examples below, you'll see the subtle difference between using Jest rather than Sinon. First is the Mocha/Sinon example and the second one is Jest: -

carbon--2-

carbon--1-

From the above code snippets, you'll see the changes were quite minor. In the example above I've demonstrated stubbing out the unix function of Moment JS. Not the complete code snippet, but below I'm cherry picking the parts where I've used Sinon to stub out the response.

import sinon from 'sinon';
....
import { fn as momentProto } from 'moment';
....
const sandbox = sinon.sandbox.create();
....
sandbox.stub(momentProto, 'unix');
....
momentProto.unix.returns(100);

Then for the same example using Jest, I implemented it in the following way: -

import { fn as momentProto } from 'moment';
....
momentProto.unix = jest.fn(() => 100);

More concise and cleaner in my opinion.

For the complete PR of how I migrated from Mocha to Jest, please head here.

I'm still getting experience writing blog posts. If you have any comments of ways I can improve these, please leave them below.

Oh for the code snippets as images above, I've used Carbon. Which I think is cool! Not consistent with the other code examples, but I just wanted to use it :)