Jest Cheat Sheetreadmemd PDF
Jest Cheat Sheetreadmemd PDF
md
github.com/sapegin/jest-cheat-sheet/blob/master/Readme.md
sapegin
1/10
Jest cheat sheet
I recommend Mrm and jest-codemods for single-command Jest installation and easy
migration from other frameworks.
Test structure
describe('makePoniesPink', () => {
beforeAll(() => {
/* Runs before all tests */
})
afterAll(() => {
/* Runs after all tests */
})
beforeEach(() => {
/* Runs before each test */
})
afterEach(() => {
/* Runs after each test */
})
Matchers
Using matchers, matchers docs
Basic matchers
Truthiness
2/10
// Matches anything that an if statement treats as true (not false, 0, '', null, undefined, NaN)
expect('foo').toBeTruthy()
// Matches anything that an if statement treats as false (false, 0, '', null, undefined, NaN)
expect('').toBeFalsy()
// Matches only null
expect(null).toBeNull()
// Matches only undefined
expect(undefined).toBeUndefined()
// The opposite of toBeUndefined
expect(7).toBeDefined()
Numbers
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)
Strings
expect('long string').toMatch('str')
expect('coffee').toMatch(/ff/)
expect('pizza').not.toMatch('coffee')
expect(['pizza', 'coffee']).toEqual([expect.stringContaining('zz'), expect.stringMatching(/ff/)])
Arrays
Objects
expect({ a: 1 }).toHaveProperty('a')
expect({ a: 1 }).toHaveProperty('a', 1)
expect({ a: { b: 1 } }).toHaveProperty('a.b')
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 })
expect({ a: 1, b: 2 }).toMatchObject({
a: expect.any(Number),
b: expect.any(Number)
})
expect([{ a: 1 }, { b: 2 }]).toEqual([
expect.objectContaining({ a: expect.any(Number) }),
expect.anything()
])
Exceptions
3/10
// const fn = () => { throw new Error('Out of cheese!') }
expect(fn).toThrow()
expect(fn).toThrow('Out of cheese')
expect(fn).toThrowErrorMatchingSnapshot()
Aliases
Snapshots
expect(node).toMatchSnapshot()
// Jest 23+
expect(user).toMatchSnapshot({
date: expect.any(Date)
})
expect(user).toMatchInlineSnapshot()
Mock functions
// const fn = jest.fn()
// const fn = jest.fn().mockName('Unicorn') -- named mock, Jest 22+
expect(fn).toBeCalled() // Function was called
expect(fn).not.toBeCalled() // Function was *not* called
expect(fn).toHaveBeenCalledTimes(1) // Function was called only once
expect(fn).toBeCalledWith(arg1, arg2) // Any of calls was with these arguments
expect(fn).toHaveBeenLastCalledWith(arg1, arg2) // Last call was with these arguments
expect(fn).toHaveBeenNthCalledWith(args) // Nth call was with these arguments (Jest 23+)
expect(fn).toHaveReturnedTimes(2) // Function was returned without throwing an error (Jest 23+)
expect(fn).toHaveReturnedWith(value) // Function returned a value (Jest 23+)
expect(fn).toHaveLastReturnedWith(value) // Last function call returned a value (Jest 23+)
expect(fn).toHaveNthReturnedWith(value) // Nth function call returned a value (Jest 23+)
expect(fn.mock.calls).toEqual([['first', 'call', 'args'], ['second', 'call', 'args']]) // Multiple calls
expect(fn.mock.calls[0][0](1)).toBe(2) // fn.mock.calls[0][0] — the first argument of the first call
Aliases
Misc
expect(new A()).toBeInstanceOf(A)
expect(() => {}).toEqual(expect.any(Function))
expect('pizza').toEqual(expect.anything())
Or with async/await:
4/10
test('resolve to lemon', async () => {
expect.assertions(2)
await expect(Promise.resolve('lemon')).resolves.toBe('lemon')
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus')
})
resolves docs
Async tests
See more examples in Jest docs.
It’s a good practice to specify a number of expected assertions in async tests, so the test
will fail if your assertions weren’t called at all.
async/await
Promises
Return a Promise from your test:
done() callback
Wrap your assertions in try/catch block, otherwise Jest will ignore failures:
5/10
test('async test', done => {
expect.assertions(1)
runAsyncOperation()
setTimeout(() => {
try {
const result = getAsyncOperationResult()
expect(result).toBe(true)
done()
} catch (err) {
done.fail(err)
}
})
})
Mocks
Mock functions
jest.mock docs
Note: When using babel-jest , calls to jest.mock will automatically be hoisted to the top of
the code block. Use jest.doMock if you want to explicitly avoid this behavior.
6/10
Mock modules using a mock file
1. Create a file like __mocks__/lodash/memoize.js :
module.exports = a => a
jest.mock('lodash/memoize')
Note: When using babel-jest , calls to jest.mock will automatically be hoisted to the top of
the code block. Use jest.doMock if you want to explicitly avoid this behavior.
const location = {}
const getTitle = jest.spyOn(location, 'title', 'get').mockImplementation(() => 'pizza')
const setTitle = jest.spyOn(location, 'title', 'set').mockImplementation(() => {})
jest.clearAllMocks()
jest.resetAllMocks()
jest.restoreAllMocks()
7/10
Accessing the original module when using mocks
jest.mock('fs')
const fs = require('fs') // Mocked module
const fs = require.requireActual('fs') // Original module
Timer mocks
Write synchronous test for code that uses native timer functions ( setTimeout ,
setInterval , clearTimeout , clearInterval ).
test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])('.add(%s, %s)', (a, b, expected) => {
expect(a + b).toBe(expected)
})
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added $b', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})
test.each() docs
Skipping tests
Don’t run these tests:
8/10
describe.skip('makePoniesPink'...
tests.skip('make each pony pink'...
describe.only('makePoniesPink'...
tests.only('make each pony pink'...
afterEach(() => {
jest.resetModules()
})
Resources
Contributing
Improvements are welcome! Open an issue or send a pull request.
9/10
CC0 1.0 Universal license, see the included License.md file.
10/10