1. Import hooks
beforeAll, afterAll, beforeEach, and afterEach are lifecycle hooks exported from bun:test.
import { test, expect, beforeAll, afterEach } from "bun:test";Typorithm · medium
Step 1 of 8 · intro card
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.
beforeAll/afterAll run once; beforeEach/afterEach per test.
toMatchSnapshot records then compares a value.
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([]); });Connect each part of the code to the concept before you type.
beforeAll, afterAll, beforeEach, and afterEach are lifecycle hooks exported from bun:test.
import { test, expect, beforeAll, afterEach } from "bun:test";beforeAll runs once before any test in the scope, ideal for one-time setup.
beforeAll(() => { db = []; });afterEach runs after every test, resetting shared state so tests stay isolated.
afterEach(() => { db.length = 0; });toMatchSnapshot stores the value on first run and compares against it on later runs.
expect({ id: 1, name: "row" }).toMatchSnapshot();test.only runs just that test; test.skip ignores one, and test.todo marks a stub.
test.only("focus here", () => { expect(db).toEqual([]); });Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.