Typorithm · medium

Hooks, Snapshots & Coverage

bun-test-lifecyclebunhookssnapshotscoverage
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Hooks, Snapshots & Coverage

0%

bun:test

Lifecycle hooks beforeAll/afterAll/beforeEach/afterEach set up and tear down state. toMatchSnapshot records a value and compares against it on reruns. Use test.skip, test.only, and test.todo to control which tests run, and bun test --coverage to measure coverage.

Lifecycle hooks — beforeAll, afterAll, beforeEach, afterEach — run setup and teardown code; beforeAll/afterAll fire once per scope, while beforeEach/afterEach run around every test to keep them isolated.

expect(value).toMatchSnapshot() writes the value to a snapshot file on the first run and compares against it on later runs, flagging any drift; test.skip, test.only, and test.todo control which tests execute.

bun test --coverage reports how much code your tests exercise, and passing a path like bun test ./foo.test.ts runs a single file.

01

beforeAll/afterAll run once; beforeEach/afterEach per test.

02

toMatchSnapshot records then compares a value.

03

bun test --coverage measures coverage.

import { test, expect, beforeAll, afterEach } from "bun:test";

let db: number[];
beforeAll(() => { db = []; });
afterEach(() => { db.length = 0; });

test("snapshot", () => {
  expect({ id: 1, name: "row" }).toMatchSnapshot();
});

test.skip("not ready", () => {});
test.only("focus here", () => { expect(db).toEqual([]); });

Read the implementation

Connect each part of the code to the concept before you type.

1. Import hooks

beforeAll, afterAll, beforeEach, and afterEach are lifecycle hooks exported from bun:test.

import { test, expect, beforeAll, afterEach } from "bun:test";

2. beforeAll setup

beforeAll runs once before any test in the scope, ideal for one-time setup.

beforeAll(() => { db = []; });

3. afterEach cleanup

afterEach runs after every test, resetting shared state so tests stay isolated.

afterEach(() => { db.length = 0; });

4. Snapshot assertion

toMatchSnapshot stores the value on first run and compares against it on later runs.

expect({ id: 1, name: "row" }).toMatchSnapshot();

5. test.only focus

test.only runs just that test; test.skip ignores one, and test.todo marks a stub.

test.only("focus here", () => { expect(db).toEqual([]); });

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Hooks, Snapshots & Coverage: Lesson & Practice · Typorithm | ApplyDjinn