Skip to content

Jest Cheatsheet

Delightful JavaScript testing framework with zero configuration.

01

Getting Started

Basic Test

test/expect for assertions.

jest
test("adds numbers", () => {
  expect(1 + 2).toBe(3);
});

Describe

describe groups related tests.

jest
describe("Math", () => {
  test("add", () => expect(1+1).toBe(2));
  test("sub", () => expect(2-1).toBe(1));
});

Matchers

Common matchers.

jest
expect(value).toBe(other);
expect(arr).toContain(item);
expect(obj).toEqual({a: 1});
expect(fn).toThrow();
expect(promise).resolves.toBe(42);
02

Features

Mock

jest.fn() creates mock functions.

jest
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn();
expect(mockFn).toHaveBeenCalled();

Async

Async tests use async/await.

jest
test("async", async () => {
  const data = await fetchData();
  expect(data).toBe("ok");
});

Before/After

Setup and teardown hooks.

jest
beforeEach(() => setup());
afterEach(() => cleanup());
afterAll(() => db.close());

Snapshot

Snapshot testing for UI components.

jest
expect(component).toMatchSnapshot();

Was this helpful?