bun test: structure, mocks and spies
Relay tells a list of notifiers about every job: Slack, email, a customer webhook. The first version
had no test, and a Slack outage turned out to stop the email notifier too, because one await threw
inside a loop. Nobody noticed for a week, because the happy path worked.
bun test is built into Bun. It runs *.test.ts files with no config and no transpile step, and it
speaks the Jest API, so most of what you know carries over. This lesson covers the parts you will
use every day, and ends with a test that proves the outage bug cannot come back.
Structure
Section titled “Structure”A file is a list of test calls. describe groups them, and the hooks run around each test:
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
interface Job { readonly id: string status: "queued" | "running"}
describe("a queue of jobs", () => { let queue: Job[]
beforeEach(() => { queue = [{ id: "j1", status: "queued" }] })
afterEach(() => { queue = [] })
test("starts with one job", () => { expect(queue).toHaveLength(1) })
test("each test gets a fresh queue", () => { queue.push({ id: "j2", status: "queued" }) expect(queue).toHaveLength(2) })})beforeEach runs before every test in the describe, so tests cannot leak state into each other.
A shared let queue that is built once at the top of the file is the classic way to get a test that
passes alone and fails in the full run.
Matchers worth knowing
Section titled “Matchers worth knowing”toBe compares with Object.is, so use it for primitives. toEqual compares structure. Beyond
those, a few matchers cover most cases:
import { expect, test } from "bun:test"
declare function parseJob(text: string): Promise<{ id: string; kind: string; attempt: number }>
test("matchers", async () => { const job = await parseJob('{"id":"j1"}') expect(job).toMatchObject({ id: "j1" }) // only the listed keys are compared expect(["email", "sms"]).toContain("sms") expect("job j1 failed").toContain("failed") expect(() => JSON.parse("{")).toThrow()})
test("promises", async () => { await expect(Promise.reject(new Error("down"))).rejects.toThrow("down") await expect(Promise.resolve({ ok: true, n: 1 })).resolves.toMatchObject({ ok: true })})Always await an expect(...).rejects or .resolves. Without await the test finishes before the
assertion runs, and a failing assertion becomes an unhandled rejection instead of a red test.
mock() records calls
Section titled “mock() records calls”mock(fn) wraps a function and remembers every call. It is the right tool for a port you pass in:
Relay’s Notifier is an interface, so a test hands over an object whose send is a mock
(ports and fakes):
import { expect, mock, test } from "bun:test"
interface Notifier { send(text: string): Promise<void>}
async function announce(notifier: Notifier, jobId: string): Promise<void> { await notifier.send(`job ${jobId} done`)}
test("announce sends one message", async () => { const send = mock(async (_text: string) => {}) await announce({ send }, "j1")
expect(send).toHaveBeenCalledTimes(1) expect(send).toHaveBeenCalledWith("job j1 done") expect(send.mock.calls).toEqual([["job j1 done"]]) // every call's arguments})The mock is typed: send.mock.calls is [text: string][], and toHaveBeenCalledWith accepts any
argument list. To make a notifier that is down, give mock a function that throws:
import { mock } from "bun:test"
const down = mock(async (_text: string): Promise<void> => { throw new Error("slack is down")})spyOn for a method that already exists
Section titled “spyOn for a method that already exists”spyOn(object, "method") replaces one method with a recording wrapper that still calls the original.
Use it when the object is real and you want to watch it, or to override just one method:
import { afterEach, expect, spyOn, test } from "bun:test"
const logger = { error: (msg: string) => console.error(msg) }
const spy = spyOn(logger, "error").mockImplementation(() => {})
afterEach(() => { spy.mockRestore() // puts the original method back})
test("the logger is called", () => { logger.error("boom") expect(spy).toHaveBeenCalledWith("boom")})A spy changes a real object, so it must be undone. spy.mockRestore() restores one spy, and
mock.restore() restores every spy at once. Forget it and the next test file in the same process
runs with your fake.
mock.module is the last resort
Section titled “mock.module is the last resort”mock.module("./notifier.ts", () => ({ ... })) replaces a whole module for everything that imports
it:
import { mock } from "bun:test"
mock.module("./slack.ts", () => ({ postToSlack: async (_text: string) => {},}))It works, and Bun even updates modules that were already imported. The cost is that it is global:
it replaces the module for every importer in the test file, mock.restore() does not undo it, and a mock
set in a --preload script applies to every test file. It also hides the dependency from the type system, so nothing checks that your replacement has
the right shape. Prefer a parameter or a port. Reach for mock.module only for a module you
cannot pass in, such as a third-party SDK called deep inside code you do not control. Lesson 4 shows
the alternative.
Running tests
Section titled “Running tests”bun test # everythingbun test src/notify # files whose path contains thisbun test -t "retry" # only tests whose name matchesbun test --watch # re-run on savebun test --coverage # print line coverage per filebun test --bail # stop at the first failureCoverage tells you which lines never ran. It does not tell you the lines that ran were checked. Lesson 3 and the exercise below are about that gap.
Exercise
Section titled “Exercise”This one is local, because it needs real bun:test mocks. Create src/dispatch.ts from the first
file below, then your own src/main.ts from the starter, and the third file as src/main.test.ts
in the Relay project from the tooling lesson. Run bun test.
You are not fixing dispatch. You write checkDispatch(impl), a test packaged as a function. The
test file runs it against the correct dispatch and against five broken ones (skips the last
notifier, stops at the first failure, sends the wrong text, wrong order, sends twice). The starter
check is too weak to see any of them, so those tests fail until yours is strict.
export interface Job { readonly id: string readonly kind: string}
export interface Notifier { send(text: string): Promise<void>}
export type Dispatch = (notifiers: readonly Notifier[], job: Job) => Promise<number>
export const dispatch: Dispatch = async (notifiers, job) => { let failed = 0 for (const notifier of notifiers) { try { await notifier.send(`${job.kind} ${job.id}`) } catch { failed++ } } return failed}// Relay's `dispatch(notifiers, job)` sends `<kind> <id>` to every notifier. You are not writing// dispatch: you are writing the TEST for it, as a function. `checkDispatch(impl)` runs any// implementation of Dispatch and throws if it misbehaves. main.test.ts runs it against the// correct dispatch (must pass) and against several broken ones (each must make it throw).//// Rules:// - A Notifier is `{ send }`. Make `send` with mock(): `mock(async (_text: string) => {})` records// its calls, and `mock(async (_text: string) => { throw new Error("down") })` is a notifier// that is down.// - Every notifier receives exactly one call, with the text `<kind> <id>`.// - The notifiers are called in the order they were given.// - A notifier that rejects does not stop the ones after it, and dispatch resolves with the// number of notifiers that failed (0 when all succeeded).// - Never rely on a real network or timer. Use the Notifier interface only.import { expect, mock } from "bun:test"import type { Dispatch, Job } from "./dispatch.ts"
const job: Job = { id: "j1", kind: "deploy" }
export async function checkDispatch(impl: Dispatch): Promise<void> { const only = mock(async (_text: string) => {}) await impl([{ send: only }], job) expect(only).toHaveBeenCalled()}import { expect, test } from "bun:test"import { dispatch } from "./dispatch.ts"import type { Dispatch } from "./dispatch.ts"import { checkDispatch } from "./main.ts"
const skipsLast: Dispatch = async (notifiers, job) => dispatch(notifiers.slice(0, -1), job)
const stopsOnFailure: Dispatch = async (notifiers, job) => { let failed = 0 for (const notifier of notifiers) { try { await notifier.send(`${job.kind} ${job.id}`) } catch { return failed + 1 } } return failed}
const wrongText: Dispatch = async (notifiers, job) => { let failed = 0 for (const notifier of notifiers) { try { await notifier.send(job.id) } catch { failed++ } } return failed}
const reversed: Dispatch = async (notifiers, job) => dispatch([...notifiers].reverse(), job)
const sendsTwice: Dispatch = async (notifiers, job) => { await dispatch(notifiers, job) return dispatch(notifiers, job)}
test("the real dispatch passes the check", async () => { await checkDispatch(dispatch)})
test("catches a dispatch that skips the last notifier", async () => { await expect(checkDispatch(skipsLast)).rejects.toThrow()})
test("catches a dispatch that stops at the first failure", async () => { await expect(checkDispatch(stopsOnFailure)).rejects.toThrow()})
test("catches a dispatch that sends the wrong text", async () => { await expect(checkDispatch(wrongText)).rejects.toThrow()})
test("catches a dispatch that calls the notifiers in reverse", async () => { await expect(checkDispatch(reversed)).rejects.toThrow()})
test("catches a dispatch that sends everything twice", async () => { await expect(checkDispatch(sendsTwice)).rejects.toThrow()})describe,test,beforeEachandafterEachgive each test a fresh state. Shared state built once at the top of a file makes order-dependent tests.toEqualfor structure,toMatchObjectfor a subset,rejectsandresolvesfor promises, always withawait.mock(fn)records calls on a port you pass in.toHaveBeenCalledWithandmock.callsread them.spyOnpatches a real object and must be restored withmockRestore()ormock.restore().mock.modulereplaces the module for every importer, survivesmock.restore()and skips the type checker: use it last.- A passing test says little. Break the code on purpose and make sure a test fails.
Further reading
Section titled “Further reading”- Bun docs: bun test: runner basics and CLI flags.
- Bun docs: Mocks: mock(), spyOn, mock.module and mock.restore.