Unit Testing with Jest: A Beginner’s Complete Guide

Unit testing with Jest starts with one idea: test a small piece of code on its own, away from the database, the network, and the rest of your app. You call a function, check what it returns, and let Jest tell you whether it matches what you expected. This guide walks you through setup, your first tests, mocks, and coverage, with code you can copy into a real project today.

You need Node.js installed and a project folder to work in. No prior testing experience is required.

Set Up Jest in a New Project

Create a folder, start an npm project, and add Jest as a development dependency. Development dependencies are the right home for test tools because they never ship to production.

mkdir jest-guide && cd jest-guide
npm init -y
npm install --save-dev jest

Open package.json and add "test": "jest" to the scripts section, so you can run tests with npm test. Run it once and Jest will report that it found no tests, which is expected. You have a working setup and an empty suite, and the next step is to give it something to test.

If your code uses ES modules or TypeScript, add a small config step. Jest works with CommonJS out of the box, and Babel or ts-jest bridges the gap for newer syntax. Check the official Jest docs for the current setup for your stack, and keep the config file short.

Unit Testing with Jest: Write Your First Test

Make a small module first, then a test file next to it. Jest picks up any file ending in .test.js by default, so naming is the only convention you have to follow.

// math.js
function add(a, b) {
  return a + b;
}

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

module.exports = { add, divide };
// math.test.js
const { add, divide } = require("./math");

test("add returns the sum of two numbers", () => {
  expect(add(2, 3)).toBe(5);
});

test("divide throws an error when dividing by zero", () => {
  expect(() => divide(10, 0)).toThrow("Cannot divide by zero");
});

Run npm test and you should see two passing tests. The pattern is always the same: arrange the inputs, call the function, and assert the result. Every test you write from here on follows that shape, no matter how large the module grows.

Notice the second test wraps the call in a function. Jest needs that wrapper so it can catch the thrown error itself. If you call divide(10, 0) directly inside expect, the error escapes before Jest can check it, and the test crashes instead of passing.

Organize Tests with describe and it

Once a file has more than a handful of tests, group them with describe blocks. Each block names the unit under test, and each it inside it states one behavior. The output reads like a spec sheet for the module, which is what you want when a test fails six months later.

// cart.test.js
const { Cart } = require("./cart");

describe("Cart", () => {
  it("starts empty", () => {
    const cart = new Cart();
    expect(cart.items).toEqual([]);
  });

  it("adds an item to the cart", () => {
    const cart = new Cart();
    cart.add({ name: "Keyboard", price: 49 });
    expect(cart.items).toHaveLength(1);
  });
});

Keep each it focused on one behavior. A test named “adds an item and calculates the total and applies a discount” is three tests hiding in one, and when it fails you will not know which part broke. Split it, name each piece clearly, and your future self will thank you.

Shared setup belongs in beforeEach. If every test builds a fresh cart, move that line into a beforeEach block so each test starts from the same clean state. That also keeps tests independent: a test that depends on another test’s leftovers will fail in confusing ways when run alone.

Matchers You Will Use Every Day

Jest matchers are the verbs of your assertions. You only need a handful of them for most code, and learning them well beats memorizing the full list.

  • toBe checks exact equality for numbers, strings, and booleans. Use it for simple values, not objects.
  • toEqual checks that two objects have the same shape and values, even if they are different instances.
  • toContain checks that an array holds a value, and toContainEqual does the same for objects inside an array.
  • toHaveLength checks the length of an array or string in one readable line.
  • toBeTruthy and toBeFalsy check truthiness when the exact value does not matter, and toThrow checks that a function throws, optionally matching the error message.

One common trap is using toBe on objects. Two objects with identical contents are still different references, so toBe fails while toEqual passes. If a test fails on an object comparison and the values look right in the output, switch to toEqual first.

Jest Async Testing Without the Headaches

Most real code is async: API calls, file reads, database queries. Jest handles all of it, but you have to tell it to wait. The cleanest way is to return the promise or use async and await in the test itself.

// user.test.js
const { fetchUser } = require("./user");

test("fetchUser returns a user with a name", async () => {
  const user = await fetchUser(1);
  expect(user.name).toBeDefined();
  expect(typeof user.id).toBe("number");
});

If a test forgets to await, it passes before the async work finishes, and a real bug hides behind a green checkmark. That is the worst kind of test failure: the silent kind. Make it a habit to check that every async test either returns a promise or uses await.

For timers, Jest gives you fake timers so you do not have to wait for real time to pass. Call jest.useFakeTimers(), advance time with jest.advanceTimersByTime(1000), and assert what happened. This keeps tests fast and removes the flakiness that comes from real clocks. Fake timers also let you control when callbacks fire, which matters once you understand how the JavaScript event loop actually works.

Jest Mock Functions and Modules

A unit test should test one unit, not the whole system behind it. When your code calls a database, an API, or a payment service, replace that dependency with a mock so the test stays fast and predictable.

// order.test.js
const { placeOrder } = require("./order");
const payment = require("./payment");

jest.mock("./payment");

test("placeOrder charges the payment service once", async () => {
  payment.charge.mockResolvedValue({ success: true });

  const result = await placeOrder({ total: 50 });
  expect(payment.charge).toHaveBeenCalledTimes(1);
  expect(payment.charge).toHaveBeenCalledWith(50);
  expect(result.paid).toBe(true);
});

jest.mock replaces the whole module with a fake version, and mockResolvedValue tells an async mock what to return. After the call, you can check how many times the mock ran and what arguments it received. Those two checks catch a large share of real integration bugs: a function that charges twice, or charges the wrong amount.

Keep mocks small and close to the test. A mock that reimplements half the real module is a second codebase to maintain, and it will drift from the real behavior. Mock the boundary, assert the interaction, and leave the rest alone.

Jest Coverage: Measure It and Read It Honestly

Run Jest with --coverage and it prints a table showing which lines, branches, functions, and statements your tests touched. The command is simple, but the number it prints needs careful reading.

Coverage tells you which code never ran during tests. That is useful: an untested branch is a place where a bug can hide unnoticed. Coverage does not tell you whether the tests that did run actually check anything. A test that calls a function and asserts nothing still counts toward coverage, which is why a high percentage can still sit on top of a weak suite.

Watch Mode and a Workflow That Sticks

Run Jest with --watch while you code and it re-runs tests related to your changed files on every save. That tight loop is what turns testing from a chore into a habit. In watch mode, press t to filter by test name and p to filter by file name.

Pair watch mode with a CI step that runs the full suite. Local watch mode catches your own mistakes fast, and CI catches the ones that only show up when your branch meets the rest of the codebase. If you build a GitHub Actions pipeline for Node.js, adding npm test as a step takes minutes and pays for itself the first time it blocks a broken merge.

FAQ

Do I need a separate config file for Jest?

Can Jest test frontend code too?

Yes, with jsdom as the test environment and a library like React Testing Library for rendering components. The patterns in this guide still apply: arrange, act, assert, and mock the network layer. Once the tests pass locally, the same Node.js app deployment guide with PM2 and Nginx covers getting the tested app onto a server.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.