Testing time and retries
Relay retries a failed delivery after 100 ms, 200 ms, 400 ms, and stops after five attempts. The
test for that took six seconds, because it called the real setTimeout, and it still passed when the
delays were wrong, since it only checked that the job eventually succeeded. Slow tests get
skipped, and a retry loop nobody tests is where outages start.
Time is an input. If the code reads it from a global, a test must wait for it or patch it. If the code is given time, a test hands it a number.
setSystemTime
Section titled “setSystemTime”For code that calls Date.now() or new Date() directly, bun:test can set the system clock:
import { afterEach, expect, setSystemTime, test } from "bun:test"
function isExpired(issuedAt: number, ttlMs: number): boolean { return Date.now() - issuedAt > ttlMs}
afterEach(() => { setSystemTime() // no argument: back to the real clock})
test("a signature older than five minutes is expired", () => { setSystemTime(new Date("2026-06-01T12:00:00Z")) const issued = Date.now() - 6 * 60_000 expect(isExpired(issued, 5 * 60_000)).toBe(true)})In Bun 1.3.10 the clock is frozen at the date you give: Date.now() returns the same value
until you change it. That is handy for a stable timestamp, but it does not make setTimeout fire.
Always reset it in afterEach, or the next test runs in 2026.
Fake timers
Section titled “Fake timers”Bun supports Jest’s fake timers through jest from bun:test. In Bun 1.3.10 these calls work, and
they are the ones this lesson uses: jest.useFakeTimers(), jest.advanceTimersByTime(ms),
jest.runAllTimers(), jest.runOnlyPendingTimers(), jest.getTimerCount(),
jest.clearAllTimers() and jest.useRealTimers(). jest.useFakeTimers({ now }) also sets Date.
Bun 1.3.10 has no advanceTimersByTimeAsync. Newer Bun versions add it; it runs pending promise jobs between timers.
import { afterEach, expect, jest, test } from "bun:test"
afterEach(() => { jest.useRealTimers()})
test("a debounced flush fires after 1 second", () => { jest.useFakeTimers() const flushed: string[] = [] setTimeout(() => flushed.push("batch"), 1000)
jest.advanceTimersByTime(999) expect(flushed).toEqual([]) jest.advanceTimersByTime(1) expect(flushed).toEqual(["batch"])})Fake timers advance Date.now() too, so code that measures elapsed time sees the jump. They work
well for a single timer. They get awkward with promises, because a timer callback and the await
that follows it run in different steps:
import { expect, jest, test } from "bun:test"
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
async function twice(): Promise<string> { await sleep(100) await sleep(200) return "done"}
test("sleeps 100 then 200", async () => { jest.useFakeTimers() const result = twice()
jest.advanceTimersByTime(100) // first sleep fires... await Promise.resolve() // ...but the second is only scheduled after the await Promise.resolve() // microtask queue has run. Each await in the code needs a tick here. jest.advanceTimersByTime(200)
expect(await result).toBe("done") jest.useRealTimers()})The number of await Promise.resolve() lines depends on how many awaits the code has between its
sleeps. Add a log line or a helper in the code under test and the test breaks. On Bun 1.3.10 that is a
sign to change the design, not the test. Newer Bun’s advanceTimersByTimeAsync removes the manual ticks,
but the test still depends on fake timers instead of an injected clock.
Inject the clock
Section titled “Inject the clock”The async lesson in M3 built a fake sleep for a typed retry. Go further: make time a port.
The retry loop takes sleep as an argument, and the rate limiter takes a Clock:
interface Clock { now(): number}
// Production: the real thing. Tests: a clock only they can move.const systemClock: Clock = { now: () => Date.now() }
function fakeClock(start = 0): Clock & { advance(ms: number): void } { let current = start return { now: () => current, advance: (ms) => void (current += ms) }}
function makeBucket(capacity: number, refillPerSec: number, clock: Clock) { let tokens = capacity let last = clock.now() return { tryTake(): boolean { const now = clock.now() tokens = Math.min(capacity, tokens + ((now - last) / 1000) * refillPerSec) last = now if (tokens < 1) return false tokens -= 1 return true }, }}
const clock = fakeClock()const bucket = makeBucket(2, 1, clock)bucket.tryTake() // truebucket.tryTake() // truebucket.tryTake() // false: emptyclock.advance(1000)bucket.tryTake() // true: one second refilled one tokenAn hour of simulated time takes a microsecond. No fake-timer API, no flakiness, no patching. It is the same idea as in dependencies as types: a clock is a port.
Test the retry schedule
Section titled “Test the retry schedule”A retry loop has two things worth testing: how many attempts happen, and how long it waits
between them. Inject sleep and record what it was asked for:
import { expect, test } from "bun:test"
async function retry<T>( op: (attempt: number) => Promise<T>, options: { maxAttempts: number; baseMs: number; sleep: (ms: number) => Promise<void> },): Promise<T> { for (let attempt = 1; ; attempt++) { try { return await op(attempt) } catch (error) { if (attempt >= options.maxAttempts) throw error await options.sleep(options.baseMs * 2 ** (attempt - 1)) } }}
test("waits 100, 200, 400 and gives up after the 4th attempt", async () => { const sleeps: number[] = [] const sleep = async (ms: number) => void sleeps.push(ms)
await expect(retry(async () => Promise.reject(new Error("down")), { maxAttempts: 4, baseMs: 100, sleep })).rejects.toThrow("down")
expect(sleeps).toEqual([100, 200, 400]) // three waits for four attempts, none after the last})Nothing waits. The test reads the schedule as data, so a wrong factor or an extra sleep after the
final attempt is a failed toEqual, not a slow test.
Time zones and DST
Section titled “Time zones and DST”Two gotchas, briefly. A date string without an offset, like "2026-03-29T02:30:00", is read in the
local zone, so the same test gives different answers on a laptop and in CI. In Europe/Berlin
that time does not exist on 29 March, because the clocks jump from 02:00 to 03:00, and
new Date(...) quietly gives 03:30. Relay stores and compares timestamps as UTC milliseconds, and
only formats for humans at the edge. When a test needs a zone, set it explicitly, at the top of
the test file:
import { expect, test } from "bun:test"
process.env.TZ = "Europe/Berlin" // before any Date is created
test("02:30 on the spring-forward day does not exist", () => { expect(new Date(2026, 2, 29, 2, 30).getHours()).toBe(3)})Exercise
Section titled “Exercise”Local, because the grading is a set of broken implementations run by bun test. Copy clock.ts,
limiter.ts and retry.ts unchanged and write your checks in main.ts.
checkBucket(make) and checkRetry(retry) are tests packaged as functions. Both use injected time:
fakeClock for the bucket, a recording sleep for the retry loop. The test file runs them against the
correct code and against broken versions: a bucket that refills past capacity, drops partial time
when polled, starts empty, or lets half a token through; a retry loop with a flat delay, one attempt
too many, a sleep after the last attempt, the wrong error, or attempts that start at 0. The
starter checks too little to see any of them.
export interface Clock { now(): number}
export function fakeClock(start = 0): Clock & { advance(ms: number): void } { let current = start return { now: () => current, advance(ms) { current += ms }, }}import type { Clock } from "./clock.ts"
export interface Bucket { tryTake(): boolean}export interface BucketOptions { readonly capacity: number readonly refillPerSec: number readonly clock: Clock}export type MakeBucket = (options: BucketOptions) => Bucket
export const makeBucket: MakeBucket = ({ capacity, refillPerSec, clock }) => { let tokens = capacity let last = clock.now() return { tryTake() { const now = clock.now() tokens = Math.min(capacity, tokens + ((now - last) / 1000) * refillPerSec) last = now if (tokens < 1) return false tokens -= 1 return true }, }}export interface RetryOptions { readonly maxAttempts: number readonly baseMs: number readonly sleep: (ms: number) => Promise<void>}export type Retry = <T>(op: (attempt: number) => Promise<T>, options: RetryOptions) => Promise<T>
export const retry: Retry = async (op, { maxAttempts, baseMs, sleep }) => { for (let attempt = 1; ; attempt++) { try { return await op(attempt) } catch (error) { if (attempt >= maxAttempts) throw error await sleep(baseMs * 2 ** (attempt - 1)) } }}// You are writing the tests for Relay's rate limiter (limiter.ts) and retry loop (retry.ts) as two// check functions. Neither may wait for real time: the bucket reads an injected Clock, the retry// loop an injected sleep. main.test.ts runs each check against the correct code (must pass) and// against broken versions (each must make it throw).//// Rules:// - checkBucket(make): use fakeClock() and make({ capacity: 3, refillPerSec: 2, clock }).// Check: a new bucket is full (3 takes succeed, the 4th fails); no time passing means no new// tokens; tokens come back with time, including fractions of a second (500 ms is one token,// 250 ms is not yet); polling often must not lose partial time (take every 300 ms and a token// appears by the second poll); an hour of idle time never gives more than `capacity` tokens.// - checkRetry(retry): op fails for the first N attempts and then succeeds. Pass a `sleep` that// records the delays and resolves at once. Check: the result is returned, op sees attempt 1, 2,// 3, ..., the recorded delays are baseMs, 2*baseMs, 4*baseMs, ..., there is no sleep after the// last attempt or after a success, there are exactly maxAttempts calls when every attempt// fails, and the rejection is the LAST attempt's error.import { expect } from "bun:test"import { fakeClock } from "./clock.ts"import type { MakeBucket } from "./limiter.ts"import type { Retry } from "./retry.ts"
export function checkBucket(make: MakeBucket): void { const clock = fakeClock() const bucket = make({ capacity: 3, refillPerSec: 2, clock }) expect(bucket.tryTake()).toBe(true)}
export async function checkRetry(retry: Retry): Promise<void> { const result = await retry(async () => "ok", { maxAttempts: 3, baseMs: 100, sleep: async () => {} }) expect(result).toBe("ok")}import { expect, test } from "bun:test"import { makeBucket } from "./limiter.ts"import type { MakeBucket } from "./limiter.ts"import { retry } from "./retry.ts"import type { Retry } from "./retry.ts"import { checkBucket, checkRetry } from "./main.ts"
const noCap: MakeBucket = ({ capacity, refillPerSec, clock }) => { let tokens = capacity let last = clock.now() return { tryTake() { const now = clock.now() tokens += ((now - last) / 1000) * refillPerSec last = now if (tokens < 1) return false tokens -= 1 return true }, }}const dropsPartialTime: MakeBucket = ({ capacity, refillPerSec, clock }) => { let tokens = capacity let last = clock.now() return { tryTake() { const now = clock.now() tokens = Math.min(capacity, tokens + Math.floor(((now - last) / 1000) * refillPerSec)) last = now if (tokens < 1) return false tokens -= 1 return true }, }}const startsEmpty: MakeBucket = ({ capacity, refillPerSec, clock }) => makeEmpty(capacity, refillPerSec, clock)function makeEmpty(capacity: number, refillPerSec: number, clock: { now(): number }) { let tokens = 0 let last = clock.now() return { tryTake() { const now = clock.now() tokens = Math.min(capacity, tokens + ((now - last) / 1000) * refillPerSec) last = now if (tokens < 1) return false tokens -= 1 return true }, }}const takesHalfTokens: MakeBucket = ({ capacity, refillPerSec, clock }) => { let tokens = capacity let last = clock.now() return { tryTake() { const now = clock.now() tokens = Math.min(capacity, tokens + ((now - last) / 1000) * refillPerSec) last = now if (tokens <= 0) return false tokens -= 1 return true }, }}
const flatDelay: Retry = async (op, { maxAttempts, baseMs, sleep }) => { for (let attempt = 1; ; attempt++) { try { return await op(attempt) } catch (error) { if (attempt >= maxAttempts) throw error await sleep(baseMs) } }}const oneTooMany: Retry = (op, options) => retry(op, { ...options, maxAttempts: options.maxAttempts + 1 })const sleepsAfterLast: Retry = async (op, { maxAttempts, baseMs, sleep }) => { for (let attempt = 1; ; attempt++) { try { return await op(attempt) } catch (error) { await sleep(baseMs * 2 ** (attempt - 1)) if (attempt >= maxAttempts) throw error } }}const firstError: Retry = async (op, { maxAttempts, baseMs, sleep }) => { let first: unknown for (let attempt = 1; ; attempt++) { try { return await op(attempt) } catch (error) { first ??= error if (attempt >= maxAttempts) throw first await sleep(baseMs * 2 ** (attempt - 1)) } }}const attemptsFromZero: Retry = (op, options) => retry((attempt) => op(attempt - 1), options)
test("the real bucket passes", () => checkBucket(makeBucket))test("catches a bucket that refills past capacity", () => expect(() => checkBucket(noCap)).toThrow())test("catches a bucket that drops partial time", () => expect(() => checkBucket(dropsPartialTime)).toThrow())test("catches a bucket that starts empty", () => expect(() => checkBucket(startsEmpty)).toThrow())test("catches a bucket that lets half a token through", () => expect(() => checkBucket(takesHalfTokens)).toThrow())
test("the real retry passes", async () => { await checkRetry(retry)})test("catches a flat delay", async () => { await expect(checkRetry(flatDelay)).rejects.toThrow()})test("catches one attempt too many", async () => { await expect(checkRetry(oneTooMany)).rejects.toThrow()})test("catches a sleep after the last attempt", async () => { await expect(checkRetry(sleepsAfterLast)).rejects.toThrow()})test("catches a retry that rejects with the first error", async () => { await expect(checkRetry(firstError)).rejects.toThrow()})test("catches attempts that start at 0", async () => { await expect(checkRetry(attemptsFromZero)).rejects.toThrow()})- Time is an input. Code that reads a global clock must be waited on or patched.
setSystemTime(date)freezesDatein Bun 1.3.10: reset it withsetSystemTime()inafterEach.jest.useFakeTimers()andadvanceTimersByTimework for single timers, but chains ofawaitneed hand-counted microtask ticks.- Inject a
Clockand asleep. Tests move the clock and record the sleeps, and take no real time. - Assert the retry schedule as data: the delays, the number of attempts, no sleep after the last.
- Store UTC milliseconds. Set
TZexplicitly when a test depends on a zone.
Further reading
Section titled “Further reading”- Bun docs: Dates and times: setSystemTime and fake timers, including the async variants in newer Bun.