Skip to content

Instantly share code, notes, and snippets.

@ra9r
Last active June 10, 2019 03:10
Show Gist options
  • Save ra9r/ff72b5f4702fd0942f8ea9c33c8664ea to your computer and use it in GitHub Desktop.
Save ra9r/ff72b5f4702fd0942f8ea9c33c8664ea to your computer and use it in GitHub Desktop.
Cheatsheet for #jest #unit-tests #mock #nodejs

Basic expectations

expect(value)
  .not
  .toBe(value)
  .toEqual(value)
  .toBeTruthy()

Note that toEqual is a deep equality check. See: expect()

Objects

expect(value)
  .toBeInstanceOf(Class)
  .toMatchObject(object)
  .toHaveProperty(keyPath, value)
expect(value)
  .toContain(item)
  .toContainEqual(item)
  .toHaveLength(number)

Snapshots

expect(value)
  .toMatchSnapshot()

Booleans

expect(value)
  .toBeFalsy()
  .toBeNull()
  .toBeTruthy()
  .toBeUndefined()
  .toBeDefined()

Numbers

expect(value)
  .toBeCloseTo(number, numDigits)
  .toBeGreaterThan(number)
  .toBeGreaterThanOrEqual(number)
  .toBeLessThan(number)
  .toBeLessThanOrEqual(number)

Strings

expect(value)
  .toMatch(regexpOrString)

Errors

expect(value)
  .toThrow(error)
  .toThrowErrorMatchingSnapshot()

Quick start

npm install --save-dev jest babel-jest
/* Add to package.json */
"scripts": {
  "test": "jest"
}
# Run your tests
npm test -- --watch

Skipping tests

describe.skip(···)
it.skip(···) // alias: xit()

Writing tests

describe('My work', () => {
  test('works', () => {
    expect(2).toEqual(2)
  })
})

BDD syntax

describe('My work', () => {
  it('works', () => {
    ···
  })
})

Setup

beforeEach(() => { ... })
afterEach(() => { ... })
beforeAll(() => { ... })
afterAll(() => { ... })

Focusing tests

describe.only(···)
it.only(···) // alias: fit()

More features

Async tests

test('works with promises', () => {
  return new Promise((resolve, reject) => {
    ···
  })
})
test('works with async/await', async () => {
  const hello = await foo()
  ···
})

Times

jest.useFakeTimers()
it('works', () => {
  jest.runOnlyPendingTimers()
  jest.runTimersToTime(1000)
  jest.runAllTimers()
})

Snapshots

First run creates a snapshot. Subsequent runs match the saved snapshot

it('works', () => {
  const output = something()
  expect(output).toMatchSnapshot()
})

React test renderer

React’s test renderer can be used for Jest snapshots.

import renderer from 'react-test-renderer'
it('works', () => {
  const tree = renderer.create(
    <Link page="http://www.facebook.com">Facebook</Link>
  ).toJSON()

  expect(tree).toMatchSnapshot()
})

Assertions

expect(fn)
  .toHaveBeenCalled()
  .toHaveBeenCalledTimes(number)
  .toHaveBeenCalledWith(arg1, arg2, ...)
  .toHaveBeenLastCalledWith(arg1, arg2, ...)
expect(fn)
  .toHaveBeenCalledWith(expect.anything())
  .toHaveBeenCalledWith(expect.any(constructor))
  .toHaveBeenCalledWith(expect.arrayContaining([ values ]))
  .toHaveBeenCalledWith(expect.objectContaining({ props }))
  .toHaveBeenCalledWith(expect.stringContaining(string))
  .toHaveBeenCalledWith(expect.stringMatching(regexp))

Mock functions

const fn = jest.fn()
const fn = jest.fn(n => n * n)

Mock Instances

const Fn = jest.fn()

a = new Fn()
b = new Fn()

Fn.mock.instances
// → [a, b]

Mock return values

const fn = jest.fn(() => 'hello')
// or
jest.fn().mockReturnValue('hello')
jest.fn().mockReturnValueOnce('hello')

Mock calls

const fn = jest.fn()
fn(123)
fn(456)

fn.mock.calls.length   // → 2
fn.mock.calls[0][0]    // → 123
fn.mock.calls[1][0]    // → 456

Mock implementations

const fn = jest.fn()
  .mockImplementationOnce(() => 1)
  .mockImplementationOnce(() => 2)
 
 
fn()    // → 1
fn()    // → 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment