Jest Cheatsheet

A list of some common Jest functions and matches that you may find helpful.

We'll cover the following

Defining tests

Grouping tests: describe('<Component />', () => {});.

Individual tests: it('does something', () => {}); or test('does something', () => {});.

Setup and teardown

beforeEach(() => {}): Runs before each test.

afterEach(() => {}): Runs after all tests.

beforeAll(() => {}): Runs once before all tests.

afterAll(() => {}): Runs once after all tests.

Assertions

expect(value) is always the first step to assert something. It contains the following functions:

  • expect(value).toBe(value): Shallow equality check
  • expect(value).toEqual(value): Deep equality check
  • expect(value).toBeTruthy() and expect(value).toBeFalsy()
  • expect(value).toBeDefined()
  • expect(value).toBeNull()
  • expect(value).toBeGreaterThan(value), expect(value).toBeGreaterThanOrEqual(value), expect(value).toBeLessThan(value), and expect(value).toBeLessThanOrEqual(value)
  • expect(value).toBeCloseTo(value, numDigits)
  • expect(value).toMatch(regex): Check a string against a regex.
  • expect(value).toContain(value): Check a data structure for containing a value.
  • expect(value).toBeInstanceOf(type): Instance check

You can also add .not to expect to flip the assertion around: expect(value).not.toEqual('abacaba') and expect(value).not.toBeInstanceOf(Abacaba)

Mocking

  • Create a mock function: jest.fn().
  • Check if a mock function was called: expect(mock).toHaveBeenCalled() and expect(mock).toHaveBeenCalledWith(args)

Get hands-on with 1400+ tech skills courses.