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.
git clone https://github.com/maurocarrero/sinon-jest-cheatsheet.git
npm install
npm test
or use watch
npm run test:watch
- Create Spies
- Are they called?
- How many times?
- Checking arguments
- Spy on objects methods
- Reset and Restore original method
- Return value
- Custom implementation
- Poking into React component methods
- Timers
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.
const spy = sinon.spy();
const spy = jest.fn();
spy.called; // boolean
spy.notCalled; // boolean
spy.mock.calls.length; // number;
expect(spy).toHaveBeenCalled();
spy.calledOnce; // boolean
spy.calledTwice; // boolean
spy.calledThrice; // boolean
spy.callCount; // number
spy.mock.calls.length; // number;
expect(spy).toHaveBeenCalledTimes(n);
// args[call][argIdx]
spy.args[0][0];
// spy.calledWith(...args)
spy.calledWith(1, 'Hey')
// 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));
sinon.spy(someObject, 'aMethod');
jest.spyOn(someObject, 'aMethod');
reset both, history and behavior:
stub.resetHistory();
reset call history:
stub.resetHistory();
reset behaviour:
stub.resetBehavior();
restore (remove mock):
someObject.aMethod.restore();
someObject.aMethod.mockRestore();
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.spyOn(operations, 'add').mockReturnValue(89);
On different calls:
spy.mockReturnValueOnce(undefined);
spy.mockReturnValueOnce(7);
expect(fn()).not.toEqual(7);
expect(fn()).toEqual(7);
sinonStub.callsFake(function() {
return 'Peteco';
});
expect(operations.add(1, 2)).toEqual('Peteco');
Different implementation on different call:
jest.spyOn(operations, 'add').mockImplementation(function(a, b, c) {
if (a === 42) {
return 89;
}
if (a === 4 && b === 9 && c === 32) {
return 'OK';
}
});
Suppose foo
is called when mounting Button.
sinon.spy(Button.prototype, 'foo');
wrapper = shallow(<Button />);
expect(Button.prototype.foo.called).toEqual(true);
jest.spyOn(Button.prototype, 'foo');
wrapper = shallow(<Button />);
expect(Button.prototype.foo).toHaveBeenCalled();
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);
Fake the date:
const clock = sinon.useFakeTimers({
now: new Date(TIMESTAMP)
});
Fake the ticks:
const clock = sinon.useFakeTimers({
toFake: ['nextTick']
});
Restore it:
clock.restore();
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();
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
});
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();
Clean obsolete snapshots:
npm t -- -u
Update snapshots:
npm t -- --updateSnapshot
expect(fn()).toMatchSnapshot();
expect(ReactTestRenderer.create(React.createElement(Button))).toMatchSnapshot();
const tree = renderer.create(<Link page="http://www.facebook.com">Facebook</Link>).toJSON();
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
// 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();
Refer to backlog.
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 ;)