Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Testing

Hooks, Snapshots, Coverage and Testing a Server

Set up and tear down with beforeAll/beforeEach, use snapshot tests, measure coverage, preload files and test a Bun.serve API on port 0 with fetch.

Once you have a few dozen tests, repeated setup code appears and you start wanting to know what is not tested. This lesson covers lifecycle hooks, snapshot tests, code coverage, project-wide test configuration and the most valuable test for any HTTP service: starting the real server and calling it.

Lifecycle hooks

Hooks run code around tests. They are imported from bun:test and scoped to the describe block (or file) they appear in.

TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";

describe("shopping cart", () => {
  let cart: Cart;

  beforeAll(() => {
    // once, before the first test of this block: start a server, open a DB
  });

  beforeEach(() => {
    cart = new Cart(); // a fresh object for EVERY test
  });

  afterEach(() => {
    // per-test cleanup: restore mocks, delete temp files
  });

  afterAll(() => {
    // once at the end: close connections, stop servers
  });

  test("starts empty", () => {
    expect(cart.items).toHaveLength(0);
  });

  test("adds an item", () => {
    cart.add({ sku: "A1", qty: 2 });
    expect(cart.items).toHaveLength(1);
  });
});

Order is predictable: beforeAll, then for each test beforeEach โ†’ test โ†’ afterEach, finally afterAll. Prefer beforeEach to build fresh state. Tests that share mutable state become order-dependent, and the failure moves around when you add a test. Hooks may be async; Bun waits for them. If beforeEach throws, the test is reported as failed.

Node.js Hook order: see the sequence (stand-in runner)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Snapshots

Sometimes you want to assert on a big output (a rendered string, an error message, a generated config) and writing every field by hand is tedious. A snapshot test stores the output the first time and compares against it afterwards.

TypeScript
import { expect, test } from "bun:test";

test("builds the config", () => {
  const config = buildConfig({ env: "prod" });
  expect(config).toMatchSnapshot(); // saved to __snapshots__/file.test.ts.snap
});

test("formats a greeting", () => {
  expect(greet("Ada")).toMatchInlineSnapshot(`"Hello, Ada!"`); // stored in the source
});

The first run writes the snapshot, and later runs fail if the value changes. If the change is intended, update the stored files with bun test --update-snapshots. Review snapshot diffs in code review like any other code; a snapshot nobody reads is a test that approves everything. Keep them small and focused, and never snapshot values that vary (timestamps, random ids, absolute paths). Normalize them first, or use property matchers such as expect.any(String) in toEqual.

Coverage

Coverage shows which lines your tests execute:

TEXT
bun test --coverage
bun test --coverage --coverage-reporter=lcov   # for CI services

Bun prints a table with percentage of functions and lines covered per file, and lists uncovered line numbers. Persist the settings in bunfig.toml:

TOML
[test]
coverage = true
coverageThreshold = 0.8     # fail the run below 80%
coverageSkipTestFiles = true
preload = ["./test/setup.ts"]
timeout = 10000

A threshold makes CI fail when coverage drops. Treat the number as a smoke detector, not a goal: 100% line coverage with weak assertions is worth less than 70% with sharp ones. Look at uncovered branches such as error handling, which is where bugs hide.

The preload file runs before every test file. Use it for global mocks, environment variables (process.env.NODE_ENV = "test") and custom matchers. Bun sets NODE_ENV=test for you under bun test.

Testing an HTTP server

The best API test is end to end: start the server on a random port, call it with fetch, check the response. It exercises routing, parsing and serialization together and takes milliseconds. Export the app so tests can start it:

TypeScript
// src/app.ts
export function createServer(port = 0) {
  return Bun.serve({
    port,
    routes: {
      "/health": () => Response.json({ ok: true }),
      "/api/echo": {
        POST: async (req) => Response.json(await req.json()),
      },
    },
  });
}
TypeScript
// src/app.test.ts
import { afterAll, beforeAll, expect, test } from "bun:test";
import { createServer } from "./app";

let server: ReturnType<typeof createServer>;
let base: string;

beforeAll(() => {
  server = createServer(0); // port 0: no clashes with other test files
  base = `http://localhost:${server.port}`;
});
afterAll(() => server.stop(true));

test("GET /health", async () => {
  const res = await fetch(`${base}/health`);
  expect(res.status).toBe(200);
  expect(await res.json()).toEqual({ ok: true });
});

test("POST /api/echo returns the body", async () => {
  const res = await fetch(`${base}/api/echo`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ hi: "there" }),
  });
  expect(await res.json()).toEqual({ hi: "there" });
});

Port 0 matters: a fixed port clashes with your running dev server, with a second test file that starts its own server, and with other jobs on a CI machine. A random free port avoids all three. Even faster: because handlers are functions from Request to Response, you can call them directly without any server: await handler(new Request("http://x/health")).

Node.js Test a handler without a server (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Practical habits

  • Name tests as sentences ("rejects an empty name"), so that a failure reads like a bug report.
  • One reason to fail per test. Several expect calls are fine when they check one behavior.
  • No order dependence: any single test must pass when run alone with -t.
  • Test failure paths: bad JSON, missing record, upstream timeout.
  • Run tests in CI with bun install --frozen-lockfile && bun test; see deploying for the pipeline basics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook runs before every single test in a block?

    beforeEach runs before each test; beforeAll runs once before the first.
  2. 2. How do you accept an intentional change in a snapshot test?

    --update-snapshots rewrites stored snapshots; the diff should still be reviewed in version control.
  3. 3. Why start a test server with port: 0?

    A random free port never collides with your dev server or other tests.
  4. 4. What does coverageThreshold = 0.8 in bunfig.toml do?

    A threshold turns coverage into a gate for CI.

Summary

  • Hooks (beforeAll, beforeEach, afterEach, afterAll) set up and clean up; build fresh state in beforeEach.
  • Snapshots store large outputs; update deliberately with --update-snapshots, keep them small and stable.
  • --coverage, coverageThreshold and preload live in bunfig.toml under [test].
  • Test APIs by starting Bun.serve on port 0 and calling it with fetch, or by calling handlers directly.
  • Write independent tests that read like sentences and cover failure paths.

Next: Bun.file and Bun.write