Awesome Open Source
Awesome Open Source

Sinon # Jest (a cheatsheet).

tested with jest code style: prettier Travis CI Build Status

Some examples on how to achieve the same goal with either of both libraries: sinon and jest. Also some of those goals achievable only by one of these tools.

What's inside? just this README file and many unit tests using jest as runner.

Clone the repo:
git clone https://github.com/maurocarrero/sinon-jest-cheatsheet.git
Install:
npm install
Run tests:
npm test

or use watch

npm run test:watch

Table of Contents

  1. Create Spies
  2. Are they called?
  3. How many times?
  4. Checking arguments
  5. Spy on objects methods
  6. Reset and Restore original method
  7. Return value
  8. Custom implementation
  9. Poking into React component methods
  10. Timers
Jest specific
  1. Snapshot testing
  2. Automock

Spies

While sinon uses three different terms for its snooping functions: spy, stub and mock, jest uses mostly the term mock function for what'd be a spy/stub and manual mock or mock ...well, for mocks.

1. Create spies:

sinon
const spy = sinon.spy();
jest
const spy = jest.fn();

2. Know if they are called:

sinon
spy.called; // boolean
spy.notCalled; // boolean
jest
spy.mock.calls.length; // number;
expect(spy).toHaveBeenCalled();

3. How many times are called:

sinon
spy.calledOnce; // boolean
spy.calledTwice; // boolean
spy.calledThrice; // boolean
spy.callCount; // number
jest
spy.mock.calls.length; // number;
expect(spy).toHaveBeenCalledTimes(n);

4. Checking arguments:

sinon
// args[call][argIdx]
spy.args[0][0];
// spy.calledWith(...args)
spy.calledWith(1, 'Hey')
jest
// mock.calls[call][argIdx]
spy.mock.calls[0][0];
expect(spy).toHaveBeenCalledWith(1, 'Hey');
expect(spy).toHaveBeenLastCalledWith(1, 'Hey');
.toHaveBeenCalledWith(expect.anything());
.toHaveBeenCalledWith(expect.any(constructor));
.toHaveBeenCalledWith(expect.arrayContaining([ values ]));
.toHaveBeenCalledWith(expect.objectContaining({ props }));
.toHaveBeenCalledWith(expect.stringContaining(string));
.toHaveBeenCalledWith(expect.stringMatching(regexp));

5. Spy on objects' methods

sinon
sinon.spy(someObject, 'aMethod');
jest
jest.spyOn(someObject, 'aMethod');

6. Reset and Restore original method

sinon

reset both, history and behavior:

stub.resetHistory();

reset call history:

stub.resetHistory();

reset behaviour:

stub.resetBehavior();

restore (remove mock):

someObject.aMethod.restore();
jest
someObject.aMethod.mockRestore();

7. Spy on method and return value:

sinon
stub = sinon.stub(operations, 'add');
stub.returns(89);
stub.withArgs(42).returns(89);
stub.withArgs(4, 9, 32).returns('OK');

On different calls:

stub.onCall(1).returns(7);
expect(fn()).not.toEqual(7);
expect(fn()).toEqual(7);
jest
jest.spyOn(operations, 'add').mockReturnValue(89);

On different calls:

spy.mockReturnValueOnce(undefined);
spy.mockReturnValueOnce(7);

expect(fn()).not.toEqual(7);
expect(fn()).toEqual(7);

8. Custom implementation:

sinon
sinonStub.callsFake(function() {
  return 'Peteco';
});
expect(operations.add(1, 2)).toEqual('Peteco');

Different implementation on different call:

jest
jest.spyOn(operations, 'add').mockImplementation(function(a, b, c) {
  if (a === 42) {
    return 89;
  }
  if (a === 4 && b === 9 && c === 32) {
    return 'OK';
  }
});

9. Poking into React components methods:

Suppose foo is called when mounting Button.

sinon
sinon.spy(Button.prototype, 'foo');

wrapper = shallow(<Button />);

expect(Button.prototype.foo.called).toEqual(true);
jest
jest.spyOn(Button.prototype, 'foo');

wrapper = shallow(<Button />);

expect(Button.prototype.foo).toHaveBeenCalled();
can be used together
const jestSpy = jest.spyOn(Button.prototype, 'doSomething');
const sinonSpy = sinon.spy(Button.prototype, 'doSomething');
wrapper = shallow(React.createElement(Button));
expect(jestSpy).toHaveBeenCalled();
expect(sinonSpy.called).toEqual(true);

10. Timers:

sinon

Fake the date:

const clock = sinon.useFakeTimers({
  now: new Date(TIMESTAMP)
});

Fake the ticks:

const clock = sinon.useFakeTimers({
  toFake: ['nextTick']
});

Restore it:

clock.restore();
jest

Enable fake timers:

jest.useFakeTimers();
setTimeout(() => {
  setTimeout(() => {
    console.log('Don Inodoro!');
  }, 200);
  console.log('Negociemos');
}, 100);

Fast-forward until all timers have been executed:

jest.runAllTimers(); // Negociemos Don Inodoro!

Run pending timers, avoid nested timers:

jest.runOnlyPendingTimers(); // Negociemos
jest.runOnlyPendingTimers(); // Don Inodoro!

Fast-forward until the value (in millis) and run all timers in the path:

jest.runTimersToTime(100); // Negociemos
jest.runTimersToTime(200); // Don Inodoro!

jest 22.0.0: .advanceTimersByTime

Clear all timers:

jest.clearAllTimers();
Date: Use Lolex

Jest does not provide a way of faking the Date, we use here lolex, a library extracted from sinon, with a implementation of the timer APIs: setTimeout, clearTimeout, setImmediate, clearImmediate, setInterval, clearInterval, requetsAnimationFrame and clearAnimationFrame, a clock instance that controls the flow of time, and a Date implementation.

clock = lolex.install({
  now: TIMESTAMP
});
Fake the ticks:
clock = lolex.install({
  toFake: ['nextTick']
});

let called = false;

process.nextTick(function() {
  called = true;
});

Forces nextTick calls to flush synchronously:

clock.runAll();

expect(called).toBeTruthy();

Trigger a tick:

clock.tick();

Restore it:

clock.uninstall();

Jest specific

1. Snapshot testing:

Clean obsolete snapshots: npm t -- -u

Update snapshots: npm t -- --updateSnapshot

snapshot of a function output
expect(fn()).toMatchSnapshot();
snapshot of a React Component (using react-test-renderer)
expect(ReactTestRenderer.create(React.createElement(Button))).toMatchSnapshot();
const tree = renderer.create(<Link page="http://www.facebook.com">Facebook</Link>).toJSON();

2. Automock

Jest disabled the automock feature by default. Enabling it again from the setup file ./tests/setupTests:

jest.enableAutomock();

Now all dependencies are mocked, we must whitelist some of them, from package.json:

"jest": {
    "unmockedModulePathPatterns": [
      "<rootDir>/src/react-component/Button.js",
      "<rootDir>/node_modules/axios",
      "<rootDir>/node_modules/enzyme",
      "<rootDir>/node_modules/enzyme-adapter-react-16",
      "<rootDir>/node_modules/react",
      "<rootDir>/node_modules/react-dom",
      "<rootDir>/node_modules/react-test-renderer",
      "<rootDir>/node_modules/sinon"
    ]
    ...

or otherwise unmock them from the test:

jest.unmock('./path/to/dep');
const Comp = require('../Comp'); // depends on dep, now will use the original
Using the mock with spies
// MOCK: path/to/original/__mocks__/myService
module.exports = {
  get: jest.fn()
};

then from the test:

const mockService = require('path/to/original/myService');
// Trigger the use of the service from tested component
wrapper.simulate('click');
expect(mockService.get).toHaveBeenCalled();

Pending work

Refer to backlog.

Contributing

Please, clone this repo and send your PR. Make sure to add your examples as unit tests and the explanation of the case into the README file. If you will add something specific of a library, make sure that is not somehow achievable with the other ;)


Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
javascript (70,303
jest (285
cheatsheet (194
unit-testing (188
mock (179
mocking (106