Skip to content

Fakes over monkey-patching

Relay’s worker test replaced globalThis.fetch with a stub and forgot to put it back. The next test file in the run called the stub, got a canned 200, and passed while the code under test was actually broken. The week after, the real job store changed its claim order, the in-memory stand-in did not, and every worker test stayed green against a store that no longer existed.

Both bugs have one cause: a replacement that nothing keeps in step with the original. This lesson removes the first with fakes, and the second with contract tests.

Patching a global or a module reaches around the function signature:

import { afterEach, expect, spyOn, test } from "bun:test"
async function notify(text: string): Promise<boolean> {
const response = await fetch("https://notifier.example.com/send", { method: "POST", body: text })
return response.ok
}
const original = globalThis.fetch
afterEach(() => {
globalThis.fetch = original // forget this and every later test sees the stub
})
test("notify returns true on 200", async () => {
spyOn(globalThis, "fetch").mockResolvedValue(new Response("ok", { status: 200 }))
expect(await notify("hi")).toBe(true)
})

Four problems. notify does not say it needs fetch, so the test must know. The patch is global, so tests cannot run concurrently. Forgetting the restore leaks into other tests. And the stub returns whatever you typed, with nothing checking it looks like a real response. The fix is the one from dependencies as types: take the capability as a parameter.

A port is the small interface a function needs. A fake is a working, simple implementation of it, not a recording stub:

interface NotifyPort {
readonly notify: { send(text: string): Promise<void> }
}
async function announce(deps: NotifyPort, jobId: string): Promise<void> {
await deps.notify.send(`job ${jobId} done`)
}
// A fake: it keeps what it was sent, and it can be told to fail.
function fakeNotify(options: { failWith?: Error } = {}) {
const sent: string[] = []
const port: NotifyPort = {
notify: {
async send(text) {
if (options.failWith !== undefined) throw options.failWith
sent.push(text)
},
},
}
return { port, sent }
}
const { port, sent } = fakeNotify()
await announce(port, "j1")
// sent is ["job j1 done"]

No patching, no restore, nothing global: each test builds its own fake, so tests run in any order or in parallel. mock() from lesson 1 is fine for asserting a single call. Reach for a fake when the test needs the dependency to behave.

Some ports have memory: a store, a queue, a rate limiter. A stub that returns a fixed value cannot express “after I enqueue a job, I can claim it, and then it is gone”. An in-memory fake can:

interface Job {
readonly id: string
readonly status: "queued" | "running"
}
interface JobStore {
enqueue(id: string): Promise<void>
claim(): Promise<Job | undefined>
}
function fakeJobStore(): JobStore {
const jobs: Job[] = []
return {
async enqueue(id) {
jobs.push({ id, status: "queued" })
},
async claim() {
const index = jobs.findIndex((job) => job.status === "queued")
const job = jobs[index]
if (job === undefined) return undefined
const running: Job = { ...job, status: "running" }
jobs[index] = running
return running
},
}
}

A worker test can now enqueue three jobs and run the worker until claim returns undefined. The fake does in twenty lines what the database does, so the test exercises Relay’s logic, not a script of canned answers.

A fake is a second implementation, and second implementations drift. The cure is to write the rules of the port once, as a function that takes any implementation, and run it against both:

import { expect, test } from "bun:test"
interface JobStore {
enqueue(id: string): Promise<void>
claim(): Promise<{ readonly id: string } | undefined>
}
// The contract: one suite for every JobStore.
async function runStoreContract(makeStore: () => JobStore): Promise<void> {
const store = makeStore()
expect(await store.claim()).toBe(undefined)
await store.enqueue("a")
await store.enqueue("b")
expect((await store.claim())?.id).toBe("a") // oldest first
expect((await store.claim())?.id).toBe("b")
expect(await store.claim()).toBe(undefined)
}
declare function fakeJobStore(): JobStore
declare function postgresJobStore(): JobStore
test("the fake follows the contract", () => runStoreContract(fakeJobStore))
// In CI only, against a real database:
test.skipIf(process.env.DATABASE_URL === undefined)("postgres follows the contract", () =>
runStoreContract(postgresJobStore),
)

Now the day someone changes the real store to claim newest-first, the contract fails against Postgres in CI, and the fix is in one place. The fake can no longer claim something the real store would not.

The contract function is a test helper: it throws on a violation, and it takes a factory so each scenario gets a fresh store.

Write both halves for Relay’s JobStore: the in-memory fake, and runStoreContract(makeStore). The rules are in the comment at the top of the starter. The tests run your contract against your fake (it must pass) and against six broken stores, each with one realistic bug: newest-first claim, a claim that leaves the job queued, silent overwrite of a duplicate id, completing a job that was never running, completing a queued job, and a get that returns the internal object. Your contract has to fail for all of them. The starter fake claims the wrong job and its contract checks one happy path.

  • Patching a global or a module hides a dependency, leaks between tests and blocks parallel runs.
  • Take the capability as a port (dependencies as types) and pass a fake.
  • A fake is a simple working implementation. Stateful fakes let a test describe a sequence.
  • Write the port’s rules once as a contract function over makeStore, and run it against the fake and the real thing.
  • A contract that only checks the happy path lets fakes and real stores drift: make it fail for each realistic bug.