Stop 12 · TestingTopics · 3/9

Jest

Part of the Backend Developer Roadmap

In short

You could test with console.log and if statements, but you'd soon want readable output, mocks and a watch mode. Jest bundles all of that into one tool you install once.

A widely used JavaScript testing framework with a built-in test runner, assertion library and mocking support — a common default for testing Node.js backends.

The blob character unzips a cricket kit bag full of bat, pads and gloves.

Think of it like this

The all-in-one cricket kit bag

A good kit bag already has the bat, pads, gloves and helmet. You don't shop for each piece before every match. Jest is that kit bag for JavaScript testing: test runner, assertions, mocks, coverage and watch mode, all in one install.

Watch it happen

What happens when you run npx jest

Find tests
Transform
Run
Expect
Report

1/5Jest finds files named *.test.ts or *.spec.ts, or anything inside __tests__ folders.

The big ideas

What you need to know

Batteries included

describe, test, expect, jest.fn mocks, fake timers and coverage all come built in.

Matchers read like English

expect(total).toBe(450), expect(list).toContain("chai"), expect(fn).toThrow().

Watch mode

npx jest --watch reruns only the tests affected by the files you just changed.

Setup and teardown

beforeEach and afterEach run around every test; beforeAll and afterAll run once per file.

See it in code

Walk through the code

ts
1import { describe, test, expect, beforeEach } from "@jest/globals";2import { Cart } from "./cart";3 4describe("Cart", () => {5  let cart: Cart;6  beforeEach(() => { cart = new Cart(); });7 8  test("starts empty", () => {9    expect(cart.items).toEqual([]);10  });11 12  test("adds items and totals them", () => {13    cart.add({ name: "samosa", price: 20 }, 3);14    expect(cart.total()).toBe(60);15  });16});

1/3describe groups related tests. beforeEach gives every test a brand-new cart.

For TypeScript, add ts-jest or babel-jest. Run npx jest once, or npx jest --watch while you code.

Save yourself the pain

Common mistakes

Oops

Using toBe to compare two objects or arrays.

Do this instead

toBe checks identity, so two equal-looking objects fail. Use toEqual to compare structure.

Oops

Forgetting to await a promise in an async test.

Do this instead

Jest may finish before your assertion runs. Make the test async and await the call.

Your mission

Your first Jest suite

~25 min

Quick check

Why does expect({ a: 1 }).toBe({ a: 1 }) fail?

Go deeper

  1. 1Write a few simple unit tests for a pure function using Jest.
  2. 2Practice mocking a module or function with `jest.fn()`/`jest.mock()`.
  3. 3Learn `describe`/`it`/`expect` — the core structure of every Jest test.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge