Stop 15 · TestingTopics · 1/8

Jest

Part of the Frontend Developer Roadmap

In short

Clicking through your app after every change gets old fast. Jest runs hundreds of small checks in seconds and shouts the moment something you didn't touch breaks.

A widely used JavaScript testing framework with a built-in test runner, assertion library and mocking support — long the default choice for testing JS/React apps.

The jaadu in a cook's cap tastes dal from a big pot in a hostel mess kitchen.

Think of it like this

The cook tasting the dal

A good mess cook tastes the dal before serving, not after 200 students complain. Jest is that taste test for your code. Every time you change the recipe, it tastes again and tells you if the salt is off.

Watch it happen

The red, green, refactor loop

Write test
Red
Code
Green
Refactor

1/5Write a test for one behaviour: placeOrder should send exactly one SMS with the item name.

The big ideas

What you need to know

test and expect

test() names a check. expect(value).toBe(x) says what should be true. If it isn't, the test fails.

Mocks fake the outside world

jest.fn() makes a fake function that records how it was called, so you don't send real SMS or hit real APIs.

Watch mode

jest --watch reruns only tests related to files you changed, so feedback comes in seconds.

Finds tests by name

By default Jest picks up files ending in .test.ts or .spec.ts, and files inside __tests__ folders.

See it in code

Walk through the code

ts
1import { placeOrder } from "./order";2 3test("sends one SMS after an order is placed", async () => {4  const sendSms = jest.fn().mockResolvedValue({ ok: true });5 6  await placeOrder({ item: "Masala Dosa", phone: "9876543210" }, sendSms);7 8  expect(sendSms).toHaveBeenCalledTimes(1);9  expect(sendSms).toHaveBeenCalledWith(10    "9876543210",11    expect.stringContaining("Masala Dosa"),12  );13});14 15// run: npx jest --watch

1/4jest.fn makes a fake sendSms that records calls and pretends to succeed.

placeOrder takes sendSms as a parameter, so the test can pass in a fake. Designing code like this makes it far easier to test.

Save yourself the pain

Common mistakes

Oops

Writing a test that has never failed.

Do this instead

Break the code on purpose once and make sure the test goes red. Otherwise it might be testing nothing.

Oops

Using toBe to compare two objects or arrays.

Do this instead

toBe checks it's the exact same object. Use toEqual to compare contents.

Your mission

Test a GST calculator

~25 min

Quick check

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

Go deeper

  1. 1Write a few simple unit tests for a pure utility function.
  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