Property-based tests with fast-check
Relay’s retry delay passed its tests for a year: attempts 0, 1, 2 gave 100, 200, 400. Then a job
failed thirty-one times in a row and the worker slept for a negative number of milliseconds, which
setTimeout treats as zero, and hammered a customer’s endpoint in a tight loop. The code used
1 << attempt, which wraps at 32 bits. No one had written a test for attempt 31, because no one
thinks of attempt 31.
An example test checks the inputs you thought of. A property test states a rule that must hold for all inputs, and a library generates hundreds of them, including the ones you did not think of.
Example vs property
Section titled “Example vs property”import { expect, test } from "bun:test"
const backoff = (attempt: number, baseMs: number, capMs: number) => Math.min(capMs, baseMs * 2 ** attempt)
test("example: attempt 2 is 400 ms", () => { expect(backoff(2, 100, 10_000)).toBe(400)})The example says nothing about attempt 31. The property says: for every attempt, the delay is at most the cap. You write the rule, not the inputs.
fc.assert(fc.property(...))
Section titled “fc.assert(fc.property(...))”fast-check is a library for this. Import it as a default import. fc.property takes arbitraries
(generators) and a function that checks one generated case. fc.assert runs it 100 times by default
and throws on the first failure, so it works inside any test:
import fc from "fast-check"import { test } from "bun:test"
const backoff = (attempt: number, baseMs: number, capMs: number) => Math.min(capMs, baseMs * 2 ** attempt)
test("the delay never exceeds the cap", () => { fc.assert( fc.property(fc.nat(300), fc.integer({ min: 1, max: 1000 }), (attempt, baseMs) => { return backoff(attempt, baseMs, 30_000) <= 30_000 }), )})The property function either returns a boolean or throws, so you can also use expect inside it.
fc.nat(300) is an integer from 0 to 300 and fc.integer({ min, max }) a bounded one.
Arbitraries for Relay data
Section titled “Arbitraries for Relay data”Build bigger values from small arbitraries. fc.record makes objects, fc.constantFrom picks from a
list, .map transforms and .filter drops values:
import fc from "fast-check"
interface Job { readonly id: string readonly kind: "email" | "sms" | "push" readonly payload: string readonly attempt: number}
export const jobs: fc.Arbitrary<Job> = fc.record({ id: fc.string({ minLength: 1 }), kind: fc.constantFrom("email", "sms", "push"), payload: fc.string(), attempt: fc.nat(),})
// Derived: a pair (base, cap) where cap >= base, built with map instead of filter.export const delays = fc .tuple(fc.integer({ min: 1, max: 1000 }), fc.nat(100_000)) .map(([baseMs, extra]) => ({ baseMs, capMs: baseMs + extra }))Prefer map to filter for constraints. filter throws values away, and a strict filter makes
generation slow. fc.string() produces printable ASCII by default, which already includes quotes,
spaces and |: the characters that break hand-written parsers.
Shrinking
Section titled “Shrinking”When a property fails, fast-check does not show you the first failure, which is usually a mess. It shrinks: it keeps trying smaller inputs that still fail, and reports the smallest one. A backoff that forgot the cap fails like this:
Property failed after 1 tests{ seed: 7, path: "0:1:0:2:2", endOnFailure: true }Counterexample: [10,5]Shrunk 4 time(s)The counter-example [10, 5] means attempt 10, base 5 ms: 5 * 2^10 = 5120, just above a 5000 ms
cap. That is a bug report you can read. Arbitraries built with map and record shrink for free.
Properties that pay
Section titled “Properties that pay”“For all inputs the output equals X” is rarely available, or it repeats the implementation. Three shapes work again and again:
- Round trip.
decode(encode(x))equalsx. It finds escaping bugs in any serializer: a|separator that appears in a payload, a trimmed space,0turned into a default. - Invariant. A fact about the output that is always true: the delay is between 0 and the cap, a queue never reports a negative length, a parsed port is between 0 and 65535.
- Relation between runs. The delay never decreases as the attempt grows. Check
f(a + 1) >= f(a), not the exact values.
A fourth shape, the model, compares a real structure with a trivially correct one. Run the same random list of commands on Relay’s job queue and on a plain array, and require the same results:
import fc from "fast-check"import { expect, test } from "bun:test"
declare class JobQueue { push(id: number): void shift(): number | undefined}
type Command = { readonly op: "push"; readonly id: number } | { readonly op: "shift" }
const commands = fc.array( fc.oneof( fc.nat().map((id): Command => ({ op: "push", id })), fc.constant<Command>({ op: "shift" }), ),)
test("the queue behaves like an array", () => { fc.assert( fc.property(commands, (list) => { const queue = new JobQueue() const model: number[] = [] for (const command of list) { if (command.op === "push") { queue.push(command.id) model.push(command.id) } else { expect(queue.shift()).toBe(model.shift()) } } }), )})A failing run shrinks to the shortest command list that shows the difference, often three or four commands.
Seeds and reproducing failures
Section titled “Seeds and reproducing failures”Every run prints a seed. A failure found by random search must be re-runnable, or you cannot fix
it. Pass the seed and the failing path to replay exactly that case:
import fc from "fast-check"
declare function property(): fc.IPropertyWithHooks<[number]>
fc.assert(property(), { seed: 7, path: "0:1:0:2:2" })Once a bug is found, also copy its shrunk counter-example into a plain example test, so it stays
covered even if the generator changes. Random testing finds the bug; an example keeps it fixed.
To look for rarer failures, raise the count with { numRuns: 1000 }.
Exercise
Section titled “Exercise”Local, because it uses fast-check (already installed in the site; in your Relay project run
bun add -d fast-check). Copy schedule.ts and codec.ts unchanged, write your checks in main.ts,
and run bun test.
checkBackoff(impl) and checkRoundTrip(codec) are property tests packaged as functions. The test
file runs each against the correct code and against broken versions: no cap, a 32-bit overflow at
large attempts, a delay that wraps back to the base, an overshoot of the cap, a |-separated
format, a decoder that trims whitespace, and attempt: 0 turned into 1. Hand-picked examples catch
none of them, so the starter fails.
export type Backoff = (attempt: number, baseMs: number, capMs: number) => number
export const backoff: Backoff = (attempt, baseMs, capMs) => Math.min(capMs, baseMs * 2 ** attempt)export interface Job { readonly id: string readonly kind: "email" | "sms" | "push" readonly payload: string readonly attempt: number}
export interface Codec { encode(job: Job): string decode(text: string): Job}
export const codec: Codec = { encode: (job) => JSON.stringify(job), decode: (text) => JSON.parse(text) as Job,}// You are writing property tests for two pieces of Relay as check functions. main.test.ts runs each// check against the correct code (must pass) and against broken versions (each must make it throw).// The broken versions are bugs that a handful of hand-picked examples never hit.//// Rules:// - checkBackoff(impl): impl(attempt, baseMs, capMs) is the retry delay. Use fc.assert and// fc.property with arbitraries for attempt (0 to a few hundred), baseMs (1 to 1000) and capMs// (>= baseMs). Properties to check: the delay is never negative and never above capMs; it never// decreases as the attempt grows; attempt 0 gives baseMs; and while below the cap it doubles.// - checkRoundTrip(codec): decode(encode(job)) equals job for every job. Build jobs with// fc.record: id from fc.string(), kind from fc.constantFrom, payload from fc.string(),// attempt from fc.nat(). Set { numRuns: 1000 } so rare characters get a chance.// - Properties must be true of the correct code for ALL inputs, or the first test fails.import fc from "fast-check"import { expect } from "bun:test"import type { Backoff } from "./schedule.ts"import type { Codec, Job } from "./codec.ts"
export function checkBackoff(impl: Backoff): void { expect(impl(0, 100, 10_000)).toBe(100) expect(impl(1, 100, 10_000)).toBe(200) expect(impl(2, 100, 10_000)).toBe(400)}
export function checkRoundTrip(codec: Codec): void { const job: Job = { id: "j1", kind: "email", payload: "hello", attempt: 1 } expect(codec.decode(codec.encode(job))).toEqual(job)}import { expect, test } from "bun:test"import { backoff } from "./schedule.ts"import type { Backoff } from "./schedule.ts"import { codec } from "./codec.ts"import type { Codec, Job } from "./codec.ts"import { checkBackoff, checkRoundTrip } from "./main.ts"
const noCap: Backoff = (attempt, baseMs) => baseMs * 2 ** attemptconst shiftOverflow: Backoff = (attempt, baseMs, capMs) => Math.min(capMs, baseMs * (1 << attempt))const wraps: Backoff = (attempt, baseMs, capMs) => backoff(attempt % 10, baseMs, capMs)const overshoots: Backoff = (attempt, baseMs, capMs) => { const previous = baseMs * 2 ** Math.max(0, attempt - 1) return previous >= capMs ? capMs : baseMs * 2 ** attempt}
const pipes: Codec = { encode: (job) => [job.id, job.kind, job.payload, job.attempt].join("|"), decode: (text) => { const [id = "", kind = "", payload = "", attempt = "0"] = text.split("|") return { id, kind: kind as Job["kind"], payload, attempt: Number(attempt) } },}const trims: Codec = { encode: codec.encode, decode: (text) => { const job = codec.decode(text) return { ...job, payload: job.payload.trim() } },}const zeroBecomesOne: Codec = { encode: codec.encode, decode: (text) => { const job = codec.decode(text) return { ...job, attempt: job.attempt || 1 } },}
test("the real backoff passes", () => checkBackoff(backoff))test("catches a backoff without a cap", () => expect(() => checkBackoff(noCap)).toThrow())test("catches a 32-bit overflow at large attempts", () => expect(() => checkBackoff(shiftOverflow)).toThrow())test("catches a backoff that wraps around", () => expect(() => checkBackoff(wraps)).toThrow())test("catches a backoff that overshoots the cap", () => expect(() => checkBackoff(overshoots)).toThrow())
test("the real codec passes", () => checkRoundTrip(codec))test("catches a separator that appears in the payload", () => expect(() => checkRoundTrip(pipes)).toThrow())test("catches a decoder that trims whitespace", () => expect(() => checkRoundTrip(trims)).toThrow())test("catches attempt 0 turning into 1", () => expect(() => checkRoundTrip(zeroBecomesOne)).toThrow())- An example test checks inputs you chose. A property states a rule for all inputs and lets
fc.assertgenerate them. fc.record,fc.constantFrom,fc.string,fc.natandfc.integerbuild Relay data. Usemapfor constraints,filtersparingly.- Shrinking turns a failure into a minimal counter-example you can read.
- Good properties: round trips, invariants, relations between runs, and a model to compare against.
- Keep the
seedof a failure, replay it, then freeze the shrunk case as an example test.
Further reading
Section titled “Further reading”- fast-check: Properties: fc.property, fc.assert and preconditions.
- fast-check: Arbitraries: the generators you build inputs from.
- fast-check: Getting started: a first property and how failures shrink.