React / 72
Your first test: test, expect and matchers
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
export function cartTotal(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}The test
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 aliasit) 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 itcartTotal.js
export const cartTotal = (items) =>items.reduce((sum, item) => sum + item.price * item.qty, 0)$ npm test · press “Run tests”
Arrange, act, assert
Most good tests follow the same three beats:
Arrange
Set up the inputs:const items = [...].Act
Run the code:const total = cartTotal(items).Assert
Check the result:expect(total).toBe(320).
Matchers you'll use most
| Matcher | Passes when | Example |
|---|---|---|
toBe(x) | Same value or same object (Object.is) | expect(sum).toBe(320) |
toEqual(x) | Same contents, checked deeply | expect(cart).toEqual({ items: [] }) |
toBeTruthy() / toBeFalsy() | Truthy / falsy | expect(isOpen).toBeFalsy() |
toContain(x) | Array has the item, or string has the text | expect(names).toContain("Dosa") |
toHaveLength(n) | .length is n | expect(items).toHaveLength(2) |
toBeCloseTo(n) | Nearly equal (for decimals) | expect(0.1 + 0.2).toBeCloseTo(0.3) |
toThrow() | The function throws | expect(() => pay(-1)).toThrow() |
.not | Flips any matcher | expect(items).not.toContain("Pizza") |
Don't
toBe on objects
expect({ items: [] }).toBe({ items: [] }); // fails: two different objectsDo
toEqual compares contents
expect({ items: [] }).toEqual({ items: [] }); // passesSetup and teardown hooks
When several tests need the same fresh data, don't copy it into each one. Hooks run code around your tests:
- beforeAll()
- beforeEach()test 1afterEach()
- beforeEach()test 2afterEach()
- afterAll()
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, orjest --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-v8the first time) orjest --coverage. It writes acoverage/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.
