}
I do JavaScript at
I also contribute to
enzyme.js
Test coverage
Snapshot testing
Assertions
easy CLI
ESNext support
Parallel tests
Dead simple API
async tests
baked in mocking
powerful and fast watch mode
meaningful error messages
babel friendly
JSDOM support
$ npm i jest -D
...
"scripts": {
"test": "jest"
},
...
package.json
Recursively looks for:
.babelrc
{
"presets": ["es2015", "react"]
}
$ npm i babel \
babel-preset-react \
babel-preset-es2017 \
babel-jest -D
describe('some test', () => {
beforeEach(() => { });
afterEach(() => { } );
it('should do something', () => {
expect(1).toBe(1);
});
});
"Jest parallelizes test runs across workers to maximize performance"
// Function spying
const spy = jest.fn();
expect(spy).toHaveBeenCalledTimes(0);
expect(spy).toHaveBeenCalledWith(arg1, arg2);
// Checking for specific params
const firstParam = spy.mock.calls[0][1];
expect(firstParam).toEqual('something');
// Function stubbing
jest
.spyOn(object, 'someMethod')
// Stubbing with implementation
jest
.spyOn(object, 'someMethod')
.mockImplementation(() => console.log('I am a mock'));
import someFn from '../someModule';
describe('some test', () => {
it('should resolve properly', () => {
return someFn().then(result => {
expect(result).toBe(...);
});
});
});
The "promise way"
import someFn from '../someModule';
describe('some test', () => {
it('should resolve properly', async () => {
await expect(someFn()).resolves.toBe(...);
});
});
async/await
import React from 'react';
export default ({ label }) => <button>{label}</button>;
import React from 'react';
import renderer from 'react-test-renderer';
import Button from '../Button';
describe('<Button />', () => {
it('should render the given label', () => {
const tree = renderer.create(<Button label='click me' />).toJSON();
expect(tree).toMatchSnapshot();
});
});
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Button /> should render the given label 1`] = `
<button>
click me
</button>
`;
Pros:
- great for testing arbitrary sets of data
- great for testing React Components
Cons:
- it can be sooooo painful
- developers tend to abuse it
jest.mock('/path/to/module', () => /* local implementation */);
or write once use everywhere
jest.mock('./utils.js');
jest.genMockFromModule(moduleName);
A good combo combined with
$ npm run coverage
...
"scripts": {
"test": "jest",
"coverage": "jest --coverage",
}
...
package.json
$ npm i -g jest-codmods
/andrei-cacio/joyful-unit-testing-with-jest
Please leave me your feedback !!!
(be gentle, or not)