3.2 KiB
3.2 KiB
Jest cheat sheet
Basic test
describe('makePoniesPink', () => {
it('should make each pony pink', () => {
const actual = fn(['Alice', 'Bob', 'Eve']);
expect(actual).toEqual(['Pink Alice', 'Pink Bob', 'Pink Eve']);
});
});
Matchers
expect.assertions(28)
expect(42).toBe(42)
expect(42).not.toBe(3)
expect([1, 2]).toEqual([1, 2])
expect('foo').toBeTruthy()
expect('').toBeFalsy()
expect(null).toBeNull()
expect(undefined).toBeUndefined()
expect(7).toBeDefined()
expect('long string').toMatch('str')
expect(result).toMatch(/regexp/)
expect({a: 1, b: 2}).toMatchObject({a: 1})
expect(2).toBeGreaterThan(1)
expect(1).toBeGreaterThanOrEqual(1)
expect(1).toBeLessThan(2)
expect(1).toBeLessThanOrEqual(1)
expect(0.2 + 0.1).toBeCloseTo(0.3, 5)
expect(['Alice', 'Bob', 'Eve']).toHaveLength(3)
expect(['Alice', 'Bob', 'Eve']).toContain('Alice')
expect([{a: 1}, {a: 2}]).toContainEqual({a: 1})
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(['Alice', 'Bob']))
expect(new A()).toBeInstanceOf(A)
expect(node).toMatchSnapshot()
expect(fn).toThrow()
expect(fn).toThrow('Out of cheese')
expect(fn).toThrowErrorMatchingSnapshot()
expect(fn).toBeCalled()
expect(fn).toHaveBeenCalledTimes(1)
expect(fn).toBeCalledWith(expect.stringContaining('foo'))
expect(fn).toBeCalledWith(expect.stringMatching(/^[A-Z]\d+$/))
expect(fn).toBeCalledWith(expect.objectContaining({x: expect.any(Number), y: expect.any(Number)}))
expect(fn).toHaveBeenLastCalledWith(expect.anything())
Mock functions
it('should call the callback', () => {
const callback = jest.fn();
fn(callback);
expect(callback).toBeCalled();
expect(callback.mock.calls[0][1].baz).toBe('pizza'); // Second argument of the first call
});
Mock modules
-
Create a file like
__mocks__/lodash/memoize.js
:module.exports = a => a;
-
Add to your test:
jest.mock('lodash/memoize');
Resources
- Jest site
- Testing React components with Jest and Enzyme by Artem Sapegin
- Testing React Applications by Max Stoiber
- Migrating to Jest by Kent C. Dodds
- Migrating AVA to Jest by Jason Brown
- How to Test React and MobX with Jest
You may also like
Contributing
Improvements are welcome! Open an issue or send a pull request.
Author and license
Artem Sapegin, a frontend developer at Here and the creator of React Styleguidist. I also write about frontend at my blog.
CC0 1.0 Universal license, see the included License.md file.