All Projects → maurocarrero → Sinon Jest Cheatsheet

maurocarrero / Sinon Jest Cheatsheet

Licence: mit
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.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Sinon Jest Cheatsheet

automock
A library for testing classes with auto mocking capabilities using jest-mock-extended
Stars: ✭ 26 (-88.5%)
Mutual labels:  mock, unit-testing, jest, mocking
Cuckoo
Boilerplate-free mocking framework for Swift!
Stars: ✭ 1,344 (+494.69%)
Mutual labels:  unit-testing, mock, mocking
Firebase Mock
Firebase mock library for writing unit tests
Stars: ✭ 319 (+41.15%)
Mutual labels:  unit-testing, mock, mocking
umock-c
A pure C mocking library
Stars: ✭ 29 (-87.17%)
Mutual labels:  mock, unit-testing, mocking
Mocktopus
Mocking framework for Rust
Stars: ✭ 179 (-20.8%)
Mutual labels:  unit-testing, mock, mocking
Graphql Query Test Mock
Easily mock GraphQL queries in your Relay Modern / Apollo / any-other-GraphQL-client tests.
Stars: ✭ 49 (-78.32%)
Mutual labels:  jest, mock, mocking
Unit Threaded
Advanced unit test framework for D
Stars: ✭ 100 (-55.75%)
Mutual labels:  unit-testing, mock, mocking
Mockery
A mock code autogenerator for Golang
Stars: ✭ 3,138 (+1288.5%)
Mutual labels:  mock, mocking
Nsubstitute
A friendly substitute for .NET mocking libraries.
Stars: ✭ 1,646 (+628.32%)
Mutual labels:  mock, mocking
Duckrails
Development tool to mock API endpoints quickly and easily (docker image available)
Stars: ✭ 1,690 (+647.79%)
Mutual labels:  mock, mocking
Snap Shot
Jest-like snapshot feature for the rest of us, works magically by finding the right caller function
Stars: ✭ 170 (-24.78%)
Mutual labels:  jest, unit-testing
Spring Data Mock
Mock facility for Spring Data repositories
Stars: ✭ 110 (-51.33%)
Mutual labels:  unit-testing, mocking
Parrot
✨ Scenario-based HTTP mocking
Stars: ✭ 109 (-51.77%)
Mutual labels:  mock, mocking
Spy
Clojure/ClojureScript library for stubs, spies and mocks.
Stars: ✭ 131 (-42.04%)
Mutual labels:  mock, mocking
Really Need
Node require wrapper with options for cache busting, pre- and post-processing
Stars: ✭ 108 (-52.21%)
Mutual labels:  mock, mocking
Mockito
Most popular Mocking framework for unit tests written in Java
Stars: ✭ 12,453 (+5410.18%)
Mutual labels:  mock, mocking
Mockery
Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL).
Stars: ✭ 10,048 (+4346.02%)
Mutual labels:  mock, mocking
Httpretty
Intercept HTTP requests at the Python socket level. Fakes the whole socket module
Stars: ✭ 1,930 (+753.98%)
Mutual labels:  mock, mocking
Fake Xrm Easy
The testing framework for Dynamics CRM and Dynamics 365 which runs on an In-Memory context and deals with mocks or fakes for you
Stars: ✭ 216 (-4.42%)
Mutual labels:  mock, mocking
Storybook Addon Jest
REPO/PACKAGE MOVED - React storybook addon that show component jest report
Stars: ✭ 177 (-21.68%)
Mutual labels:  jest, unit-testing

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 ;)

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].