Skip to content
ClapelloNotes by Barath
ReactCh 13 · 3/6
Beginner4 min readUpdated

React / 72

Your first test: test, expect and matchers

TL;DR

A test calls your code and checks the result with expect(…).toBe(…). Group tests with describe, share setup with beforeEach, and run them on every save.

The code we'll test

src/utils/cartTotal.js
export function cartTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

The test

src/utils/cartTotal.test.js
import { cartTotal } from "./cartTotal";
 
describe("cartTotal", () => {
  it("is 0 for an empty cart", () => {
    expect(cartTotal([])).toBe(0);
  });
 
  it("multiplies price by quantity", () => {
    const items = [
      { price: 120, qty: 2 },
      { price: 80, qty: 1 },
    ];
    expect(cartTotal(items)).toBe(320);
  });
});
  • test(name, fn) (or its alias it) is one check. The name should read like a sentence about behaviour.
  • describe(name, fn) groups related tests. Names join up in the output: cartTotal › multiplies price by quantity.
  • expect(value) wraps the actual result; a matcher like .toBe(320) states what it should be. If they differ, the test fails and shows both values.

describe, it and expect work without imports because we turned on globals (Vitest) or use Jest's defaults. You can also import them: import { describe, it, expect } from "vitest" (or from "@jest/globals").

Run it with npm test. Now try breaking the code:

Run the tests

Try it

cartTotal.js

export const cartTotal = (items) =>items.reduce((sum, item) => sum + item.price * item.qty, 0)

$ npm test · press “Run tests”

The runner output here is simulated, but the checks are real: each test calls cartTotal and compares with Object.is, like toBe. Break the code and only the test that covers quantity fails.

Arrange, act, assert

Most good tests follow the same three beats:

  1. Arrange

    Set up the inputs: const items = [...].
  2. Act

    Run the code: const total = cartTotal(items).
  3. Assert

    Check the result: expect(total).toBe(320).

Matchers you'll use most

MatcherPasses whenExample
toBe(x)Same value or same object (Object.is)expect(sum).toBe(320)
toEqual(x)Same contents, checked deeplyexpect(cart).toEqual({ items: [] })
toBeTruthy() / toBeFalsy()Truthy / falsyexpect(isOpen).toBeFalsy()
toContain(x)Array has the item, or string has the textexpect(names).toContain("Dosa")
toHaveLength(n).length is nexpect(items).toHaveLength(2)
toBeCloseTo(n)Nearly equal (for decimals)expect(0.1 + 0.2).toBeCloseTo(0.3)
toThrow()The function throwsexpect(() => pay(-1)).toThrow()
.notFlips any matcherexpect(items).not.toContain("Pizza")

Don't

toBe on objects

expect({ items: [] }).toBe({ items: [] }); // fails: two different objects

Do

toEqual compares contents

expect({ items: [] }).toEqual({ items: [] }); // passes

Setup and teardown hooks

When several tests need the same fresh data, don't copy it into each one. Hooks run code around your tests:

  1. beforeAll()
  2. beforeEach()
    test 1
    afterEach()
  3. beforeEach()
    test 2
    afterEach()
  4. afterAll()
beforeAll / afterAll run once per file (or describe block). beforeEach / afterEach wrap every single test, so each test starts fresh.
import { cartTotal } from "./cartTotal";
 
let items;
 
beforeEach(() => {
  items = [{ price: 100, qty: 1 }]; // a fresh array for every test
});
 
it("adds one more", () => {
  items.push({ price: 50, qty: 1 });
  expect(cartTotal(items)).toBe(150);
});
 
it("still starts from one item", () => {
  expect(cartTotal(items)).toBe(100); // not affected by the push above
});

Use beforeEach/afterEach for things that must be fresh per test (data, mocks); beforeAll/afterAll for slow one-time setup (starting a mock server).

Watch mode and coverage

  • Watch mode (vitest, or jest --watch) re-runs affected tests on every save. Keep it open while you work.
  • test.only(...) runs just that test while you debug; test.skip(...) skips one. Don't commit either.
  • Coverage shows which lines your tests ran: vitest run --coverage (it asks to install @vitest/coverage-v8 the first time) or jest --coverage. It writes a coverage/ folder with an HTML report; keep it out of git.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.