• Stars
    star
    5,071
  • Rank 8,205 (Top 0.2 %)
  • Language
  • License
    Creative Commons ...
  • Created almost 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Jest cheat sheet

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 */
  })

  test('make each pony pink', () => {
    const actual = fn(['Alice', 'Bob', 'Eve'])
    expect(actual).toEqual(['Pink Alice', 'Pink Bob', 'Pink Eve'])
  })
})

Matchers

Using matchers, matchers docs

Basic matchers

expect(42).toBe(42) // Strict equality (===)
expect(42).not.toBe(3) // Strict equality (!==)
expect([1, 2]).toEqual([1, 2]) // Deep equality
expect({ a: undefined, b: 2 }).toEqual({ b: 2 }) // Deep equality
expect({ a: undefined, b: 2 }).not.toStrictEqual({ b: 2 }) // Strict equality (Jest 23+)

Truthiness

// 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()
// Matches true or false
expect(true).toEqual(expect.any(Boolean))

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)
expect(NaN).toEqual(expect.any(Number))

Strings

expect('long string').toMatch('str')
expect('string').toEqual(expect.any(String))
expect('coffee').toMatch(/ff/)
expect('pizza').not.toMatch('coffee')
expect(['pizza', 'coffee']).toEqual([expect.stringContaining('zz'), expect.stringMatching(/ff/)])

Arrays

expect([]).toEqual(expect.any(Array))
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']))

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

// const fn = () => { throw new Error('Out of cheese!') }
expect(fn).toThrow()
expect(fn).toThrow('Out of cheese')
expect(fn).toThrowErrorMatchingSnapshot()
Aliases
  • toThrowErrortoThrow

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(callNumber, 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]).toBe(2) // fn.mock.calls[0][0] — the first argument of the first call
Aliases
  • toBeCalledtoHaveBeenCalled
  • toBeCalledWithtoHaveBeenCalledWith
  • lastCalledWithtoHaveBeenLastCalledWith
  • nthCalledWithtoHaveBeenNthCalledWith
  • toReturnTimestoHaveReturnedTimes
  • toReturnWithtoHaveReturnedWith
  • lastReturnedWith → toHaveLastReturnedWith
  • nthReturnedWith → toHaveNthReturnedWith

Misc

expect(new A()).toBeInstanceOf(A)
expect(() => {}).toEqual(expect.any(Function))
expect('pizza').toEqual(expect.anything())

Promise matchers (Jest 20+)

test('resolve to lemon', () => {
  expect.assertions(1)
  // Make sure to add a return statement
  return expect(Promise.resolve('lemon')).resolves.toBe('lemon')
  return expect(Promise.reject('octopus')).rejects.toBeDefined()
  return expect(Promise.reject(Error('pizza'))).rejects.toThrow()
})

Or with async/await:

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.

test('async test', () => {
  expect.assertions(3) // Exactly three assertions are called during a test
  // OR
  expect.hasAssertions() // At least one assertion is called during a test

  // Your async tests
})

Note that you can also do this per file, outside any describe and test:

beforeEach(expect.hasAssertions)

This will verify the presense of at least one assertion per test case. It also plays nice with more specific expect.assertions(3) declarations.

In addition, you can enforce it globally, across all test files (instead of having to repeat per file) by adding the exact same line into one of the scripts referenced by the setupFilesAfterEnv configuration option. (For example, setupTests.ts and that is referenced via a setupFilesAfterEnv: ['<rootDir>/setupTests.ts'] entry in jest.config.ts.)

async/await

test('async test', async () => {
  expect.assertions(1)
  const result = await runAsyncOperation()
  expect(result).toBe(true)
})

Promises

Return a Promise from your test:

test('async test', () => {
  expect.assertions(1)
  return runAsyncOperation().then((result) => {
    expect(result).toBe(true)
  })
})

done() callback

Wrap your assertions in try/catch block, otherwise Jest will ignore failures:

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

test('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
  // Match the first and the last arguments but ignore the second argument
  expect(callback).toHaveBeenLastCalledWith('meal', expect.anything(), 'margarita')
})

You can also use snapshots:

test('call the callback', () => {
  const callback = jest.fn().mockName('Unicorn') // mockName is available in Jest 22+
  fn(callback)
  expect(callback).toMatchSnapshot()
  // ->
  // [MockFunction Unicorn] {
  //   "calls": Array [
  // ...
})

And pass an implementation to jest.fn function:

const callback = jest.fn(() => true)

Mock functions docs

Returning, resolving and rejecting values

Your mocks can return values:

const callback = jest.fn().mockReturnValue(true)
const callbackOnce = jest.fn().mockReturnValueOnce(true)

Or resolve values:

const promise = jest.fn().mockResolvedValue(true)
const promiseOnce = jest.fn().mockResolvedValueOnce(true)

They can even reject values:

const failedPromise = jest.fn().mockRejectedValue('Error')
const failedPromiseOnce = jest.fn().mockRejectedValueOnce('Error')

You can even combine these:

const callback = jest.fn().mockReturnValueOnce(false).mockReturnValue(true)

// ->
//  call 1: false
//  call 2+: true

Mock modules using jest.mock method

jest.mock('lodash/memoize', () => (a) => a) // The original lodash/memoize should exist
jest.mock('lodash/memoize', () => (a) => a, { virtual: true }) // The original lodash/memoize isn’t required

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.

Mock modules using a mock file

  1. Create a file like __mocks__/lodash/memoize.js:

    module.exports = (a) => a
  2. Add to your test:

    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.

Manual mocks docs

Mock object methods

const spy = jest.spyOn(console, 'log').mockImplementation(() => {})
expect(console.log.mock.calls).toEqual([['dope'], ['nope']])
spy.mockRestore()
const spy = jest.spyOn(ajax, 'request').mockImplementation(() => Promise.resolve({ success: true }))
expect(spy).toHaveBeenCalled()
spy.mockRestore()

Mock getters and setters (Jest 22.1.0+)

const location = {}
const getTitle = jest.spyOn(location, 'title', 'get').mockImplementation(() => 'pizza')
const setTitle = jest.spyOn(location, 'title', 'set').mockImplementation(() => {})

Mock getters and setters

const getTitle = jest.fn(() => 'pizza')
const setTitle = jest.fn()
const location = {}
Object.defineProperty(location, 'title', {
  get: getTitle,
  set: setTitle,
})

Clearing and restoring mocks

For one mock:

fn.mockClear() // Clears mock usage date (fn.mock.calls, fn.mock.instances)
fn.mockReset() // Clears and removes any mocked return values or implementations
fn.mockRestore() // Resets and restores the initial implementation

Note: mockRestore works only with mocks created by jest.spyOn.

For all mocks:

jest.clearAllMocks()
jest.resetAllMocks()
jest.restoreAllMocks()

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

// Enable fake timers
jest.useFakeTimers()

test('kill the time', () => {
  const callback = jest.fn()

  // Run some code that uses setTimeout or setInterval
  const actual = someFunctionThatUseTimers(callback)

  // Fast-forward until all timers have been executed
  jest.runAllTimers()

  // Check the results synchronously
  expect(callback).toHaveBeenCalledTimes(1)
})

Or adjust timers by time with advanceTimersByTime():

// Enable fake timers
jest.useFakeTimers()

test('kill the time', () => {
  const callback = jest.fn()

  // Run some code that uses setTimeout or setInterval
  const actual = someFunctionThatUseTimers(callback)

  // Fast-forward for 250 ms
  jest.advanceTimersByTime(250)

  // Check the results synchronously
  expect(callback).toHaveBeenCalledTimes(1)
})

Use jest.runOnlyPendingTimers() for special cases.

Note: you should call jest.useFakeTimers() in your test case to use other fake timer methods.

Data-driven tests (Jest 23+)

Run the same test with different data:

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
])('.add(%s, %s)', (a, b, expected) => {
  expect(a + b).toBe(expected)
})

Or the same using template literals:

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

Or on describe level:

describe.each([['mobile'], ['tablet'], ['desktop']])('checkout flow on %s', (viewport) => {
  test('displays success page', () => {
    //
  })
})

describe.each() docs, test.each() docs,

Skipping tests

Don’t run these tests:

describe.skip('makePoniesPink'...
tests.skip('make each pony pink'...

Run only these tests:

describe.only('makePoniesPink'...
tests.only('make each pony pink'...

Testing modules with side effects

Node.js and Jest will cache modules you require. To test modules with side effects you’ll need to reset the module registry between tests:

const modulePath = '../module-to-test'

afterEach(() => {
  jest.resetModules()
})

test('first test', () => {
  // Prepare conditions for the first test
  const result = require(modulePath)
  expect(result).toMatchSnapshot()
})

test('second text', () => {
  // Prepare conditions for the second test
  const fn = () => require(modulePath)
  expect(fn).toThrow()
})

Usage with Babel and TypeScript

Add babel-jest or ts-jest. Check their docs for installation instructions.

Resources


You may also like

Contributing

Improvements are welcome! Open an issue or send a pull request.

Sponsoring

This software has been developed with lots of coffee, buy me one more cup to keep it going.

Buy Me A Coffee

Author and license

Artem Sapegin, a frontend engineer at Omio 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.

More Repositories

1

mrm

Codemods for your project config files
JavaScript
1,612
star
2

grunt-webfont

SVG to webfont converter for Grunt
JavaScript
1,104
star
3

social-likes

Beautiful social “like” buttons with counters for jQuery.
CSS
1,089
star
4

shipit

Minimalistic SSH deployment
Shell
558
star
5

dotfiles

My macOS environment: zsh, Git, Visual Studio Code, etc.
Shell
463
star
6

jquery.mosaicflow

Pinterest like responsive image grid that doesn’t suck
HTML
307
star
7

grunt-bower-concat

Bower components concatenator for Grunt
JavaScript
219
star
8

react-components

List of React components I use and recommend
193
star
9

washingcode-book

📖 Book on clean code for frontend developers
JavaScript
175
star
10

social-likes-next

Beautiful modern share buttons
JavaScript
163
star
11

stack-styled

Stacking layouts for React
TypeScript
141
star
12

richtypo.js

Typography enhancer for Node.js
TypeScript
123
star
13

fledermaus

Batman’s toolbelt for static site generation
JavaScript
78
star
14

q-i

Node.js objects inspector with color highlighting
JavaScript
62
star
15

react-spaceman

React component to manage whitespace
TypeScript
61
star
16

proselint

Proselint wrapper with a friendly reporter
JavaScript
60
star
17

squirrelsong

Low contrast light & dark themes
Vim Script
51
star
18

react-group

Render React children with a separator
JavaScript
48
star
19

textlint-rule-terminology

Textlint rule to check correct terms spelling
TypeScript
47
star
20

react-weather

React/alt/ES6/Webpack demo app
JavaScript
41
star
21

blog.sapegin.me

My tech blog
TypeScript
38
star
22

bower-update

DEPRECATED. Updates Bower components to the really latest versions.
JavaScript
37
star
23

mrm-core

Utilities to make tasks for Mrm
JavaScript
33
star
24

frontend-pull-request-checklist

Frontend pull request checklist
33
star
25

mrm-tasks

Mrm tasks: codemods for your config files
JavaScript
32
star
26

sweet

Simplest Web Engine Ever, The
JavaScript
29
star
27

fontoptim

Generates CSS with WOFF(2) fonts embedded as Base64
HTML
25
star
28

squirrelstrap

Set of Grunt templates for faster front-end web development
PHP
22
star
29

textlint-rule-stop-words

Textlint rule to find filler words, buzzwords and clichés
JavaScript
22
star
30

expect-react-shallow

JSX assertions with Chai-like API (based on unexpected-react-shallow)
JavaScript
20
star
31

grunt-fingerprint

Assets versioning task for Grunt
JavaScript
19
star
32

picturebeaver

WSH script for batch optimization PNG/JPEG/GIF images using optipng/jpegtran/gifsicle utilities.
19
star
33

csso-stylus

CSSO plugin for Stylus.
CoffeeScript
16
star
34

grunt-fontoptim

Generates CSS with WOFF(2) fonts embedded as Base64
JavaScript
16
star
35

morning.photos

My photo gallery
TypeScript
15
star
36

user-meta

Read user name, email and URL from .npmrc or .gitconfig
JavaScript
14
star
37

grunt-shower-markdown

Grunt task that generates Shower presentations from Markdown source
JavaScript
14
star
38

grunt-imgo

Image optimization for Grunt using imgo
JavaScript
13
star
39

csscolors

All named CSS colors on a single page
HTML
12
star
40

cddcourse

Component-driven development course
JavaScript
12
star
41

PEW

Photoshop Export Workflow: simple Photoshop scripts for file saving automation
JavaScript
12
star
42

sapegin.me

My home page and blog
TypeScript
12
star
43

grunt-stylus

DEPRECATED. Stylus task for Grunt
JavaScript
11
star
44

rtl-article-2019

Modern React testing: Jest and Enzyme
JavaScript
11
star
45

react-pixel-gif

1×1 pixel GIF component for React
JavaScript
9
star
46

react-text-stats

React/alt/ES6/Webpack/Jest demo app
JavaScript
8
star
47

coffeetimer

Basic filter coffee timer web app
TypeScript
8
star
48

react-pagify-preset-bootstrap

Bootstrap preset for react-pagify
JavaScript
8
star
49

grunt-article-examples

Тестовый Грант-проект
JavaScript
8
star
50

hello-box-flex-stack

“Say hello to Box, Flex and Stack: layouts in the component era” talk slides
JavaScript
7
star
51

cypress-article-2020

Modern React testing article examples: Cypress and Cypress Testing Library
JavaScript
6
star
52

enzyme-article-2019

Modern React testing: Jest and Enzyme
JavaScript
6
star
53

textlint-rule-apostrophe

Textlint rule to check correct apostrophe usage
JavaScript
5
star
54

hashnav

Simplest JavaScript hash navigation.
JavaScript
5
star
55

writing-style

English style guide
5
star
56

smpltmpl

Simple templates for Node.js based on ECMAScript template literals syntax
JavaScript
5
star
57

textlint-rule-title-case

Textlint rule to ensure that titles are using AP/APA style
JavaScript
5
star
58

every.morning.photos

My Instagram photos made on this day
TypeScript
5
star
59

lightroom-book-ru

Разумный рабочий процесс в Lightroom
5
star
60

textlint-rule-diacritics

Textlint rule to check correct usage of diacritics
JavaScript
4
star
61

til

Today I learned
4
star
62

grunt-talk-examples

Примеры к докладу про Grunt
PHP
4
star
63

deabsdeep

Recursively replace absolute paths in objects and arrays with ~
JavaScript
3
star
64

slides

Slides from my talks
HTML
3
star
65

package-repo-url

Returns GitHub repository URL based on package.json.
JavaScript
3
star
66

jquery-nicehover

jQuery delayed hover event
JavaScript
2
star
67

instagram-poster

Script to post photos to Instagram
JavaScript
2
star
68

egghead-typescript-webpack-css-modules

How to use CSS Modules with TypeScript and webpack
JavaScript
2
star
69

SublimeGruntWatch

Grunt Watch plugin for Sublime Text 2
Python
2
star
70

social-share-services

Social share sites data: icon, popup URL, etc.
JavaScript
2
star
71

grunt-sweet

Sweet task for Grunt
HTML
2
star
72

jscodestyle

What JavaScript code style is the most popular
HTML
2
star
73

git-default-branch

Returns Git default branch name
JavaScript
2
star
74

vscode-just-blame

VS Code extension to show Git Blame annotations, inspired by JetBrains editors 🪲
TypeScript
1
star
75

fingerprinter

Generic assests fingerprint generator
CSS
1
star
76

cv

My résumé
HTML
1
star
77

wp-typohelper

Russian typography for WordPress
PHP
1
star
78

vscode-new-file-now

Visual Studio Code extension to create new files from the command palette 🆕
TypeScript
1
star
79

vitest-cheat-sheet

Vitest cheat sheet
1
star
80

home-assistant-config

My Home Assistant config
Python
1
star
81

gatsby-lessons

Egghead lessons on Gatsby
CSS
1
star
82

fog.morning.photos

Is it foggy in Berlin?
TypeScript
1
star