Skip to content

Property-based testing in TypeScript with fast-check: shrinking and model-based tests

Property-based testing with fast-check: choosing properties, reading shrunk counterexamples, replaying failures and testing stateful code against a model.

· 7 min read

  • Testing
  • TypeScript
  • Property-based testing

Example-based tests check the cases you thought of. Bugs live in the ones you did not. A property-based test states a rule that must hold for every input, then generates hundreds of inputs to try to break it. When it finds one, it shrinks the input to something small enough to read.

We use this on smart contracts, where it is called fuzz and invariant testing, and on ordinary application code. This article uses fast-check, the main library for TypeScript and JavaScript. Every snippet below was run on Node 22 with fast-check 4.10.2, and the output shown is real, with the library’s trailing hint line trimmed.

A first property: splitting money

A classic bug: dividing a bill between several people and losing pennies. Amounts are integers in pence.

export function split(total: number, parts: number): number[] {
  const share = Math.floor(total / parts);
  return Array.from({ length: parts }, () => share);
}

A unit test with split(100, 4) passes. So does split(90, 3). Both divide evenly, which is exactly the case the author had in mind. Now state what must always be true:

import fc from "fast-check";

fc.assert(
  fc.property(
    fc.integer({ min: 0, max: 1_000_000 }),
    fc.integer({ min: 1, max: 20 }),
    (total, parts) => {
      const out = split(total, parts);
      const sum = out.reduce((a, b) => a + b, 0);
      return (
        out.length === parts &&
        sum === total &&
        Math.max(...out) - Math.min(...out) <= 1
      );
    },
  ),
);

Three rules: there are parts shares, they add up to total, and nobody gets more than one penny more than anybody else. Running it:

Property failed after 1 tests
{ seed: 959225073, path: "0:2:0:2:0:0:1:0:0:0:1", endOnFailure: true }
Counterexample: [595791,2]
Shrunk 10 time(s)

It failed on the first generated input. The fix spreads the remainder:

export function split(total: number, parts: number): number[] {
  const base = Math.floor(total / parts);
  const extra = total % parts;
  return Array.from({ length: parts }, (_, i) => base + (i < extra ? 1 : 0));
}

With that, the property passes its default 100 runs. Raise numRuns in the second argument of fc.assert for something you care about.

Two things in that output are worth understanding.

Shrinking is greedy, not perfect

The first failing input was random and large. fast-check tried smaller variants of it ten times, keeping each one that still failed, and stopped at [595791, 2]. The smallest possible failure is [1, 2], so this seed got stuck. Shrinking is a greedy search: it moves to a simpler failing input when it can, and stops when no single step does. Here every smaller candidate it offered (595776, 595784, 595788, 595790) was even, and even totals split evenly in two, so they passed. Across 200 random seeds on this property, 144 reached [1, 2]; the rest stopped at cases such as [3, 2] or [10, 3].

So do not rely on the counterexample being minimal. Treat it as a readable case, and ask what is special about it. Here, an odd total split two ways. If the failure is not clear from the shrunk value, add a second, narrower property, or fix the generator so it favours the edge you suspect.

Replaying a failure

The seed and path in the output reproduce the failure. Passing them back replays that path and shrinks on from there:

const prop = fc.property(/* the arbitraries and check from above */);
fc.assert(prop, { seed: 959225073, path: "0:2:0:2:0:0:1:0:0:0:1" });

With the seed alone, fast-check regenerates the same sequence and shrinks again, so the counterexample is the same. Adding the path jumps straight to the shrunk value; we saw Shrunk 0 time(s) and the same [595791,2]. Replay only works if the property is deterministic, so keep Date.now() and Math.random() out of generators and properties.

Once a failure is understood, turn it into a plain example test as well. fast-check can also pin examples with the examples option of fc.assert, but a normal test named after the bug is easier for the next person to find. The random search finds the bug; the example stops it coming back.

Finding properties worth writing

The hard part is choosing the rule. Most useful properties are one of a handful of shapes:

  • Round trip. Encode then decode returns the input. Serialisers, parsers, URL builders, migrations that have a reverse.
  • Invariant. Something stays true whatever happens: totals are conserved, a list stays sorted, a balance never goes negative. The split property above is this.
  • Idempotence. Doing it twice is the same as doing it once: normalising an email, sorting, applying an event with a stable ID. See idempotent payment webhooks for where this matters.
  • Oracle. A slow, obvious implementation agrees with the fast, clever one. This is the next section.
  • Metamorphic. You cannot say what the output is, but you can say how it changes when the input changes: adding a filter never returns more rows.

If you can only write expect(f(x)).toEqual(whatTheCodeDoes(x)), you are repeating the implementation, not testing it. Pick a weaker rule that is still true.

Testing stateful code against a model

Properties on pure functions are the easy case. The more valuable one is a stateful component, such as a cache, a queue or a shopping basket, where bugs depend on the order of operations. fast-check handles this with model-based testing: generate a sequence of commands, run each against the real thing and against a deliberately simple model, and compare.

Take a small least-recently-used cache built on Map, which iterates in insertion order. This version has a bug: updating an existing key does not refresh its recency.

class Lru {
  private m = new Map<string, number>();
  constructor(private cap: number) {}

  get(k: string) {
    if (!this.m.has(k)) return undefined;
    const v = this.m.get(k)!;
    this.m.delete(k);
    this.m.set(k, v); // mark as most recent
    return v;
  }

  set(k: string, v: number) {
    if (this.m.has(k)) { this.m.set(k, v); return; } // bug: stays in old position
    this.m.set(k, v);
    if (this.m.size > this.cap) this.m.delete(this.m.keys().next().value!);
  }
}

The model is an array, oldest first. It is slow and obviously right:

class Model {
  private a: [string, number][] = [];
  constructor(private cap: number) {}
  get(k: string) {
    const i = this.a.findIndex(([x]) => x === k);
    if (i < 0) return undefined;
    const [e] = this.a.splice(i, 1);
    this.a.push(e);
    return e[1];
  }
  set(k: string, v: number) {
    const i = this.a.findIndex(([x]) => x === k);
    if (i >= 0) this.a.splice(i, 1);
    this.a.push([k, v]);
    if (this.a.length > this.cap) this.a.shift();
  }
}

Each command is a small class with check and run, and it compares what the two return:

class GetCmd implements fc.Command<Model, Lru> {
  constructor(readonly k: string) {}
  check = () => true;
  run(m: Model, r: Lru) {
    if (m.get(this.k) !== r.get(this.k)) throw new Error(`get(${this.k}) differs`);
  }
  toString = () => `get(${this.k})`;
}

class SetCmd implements fc.Command<Model, Lru> {
  constructor(readonly k: string, readonly v: number) {}
  check = () => true;
  run(m: Model, r: Lru) { m.set(this.k, this.v); r.set(this.k, this.v); }
  toString = () => `set(${this.k}, ${this.v})`;
}

const keys = fc.constantFrom("a", "b", "c", "d");
const commands = [
  fc.tuple(keys, fc.nat(9)).map(([k, v]) => new SetCmd(k, v)),
  keys.map((k) => new GetCmd(k)),
];

fc.assert(
  fc.property(fc.commands(commands, { maxCommands: 30 }), (cmds) => {
    fc.modelRun(() => ({ model: new Model(2), real: new Lru(2) }), cmds);
  }),
);

Run with the default 100 runs, this bug is found only most of the time: it failed in 15 of 20 unseeded runs of the script (a second batch gave 13 of 20), at any point in the 100 sequences. With { numRuns: 1000 } it failed in 20 of 20. A passing run of a property is weaker evidence than it looks, so give stateful tests more runs than pure ones. A failing run looks like this (the exact sequence varies between runs, and the hint line is trimmed):

Counterexample: [set(a, 0),set(d, 0),set(a, 0),set(c, 0),get(a) /*replayPath="..."*/]

Read it as a story. With room for two entries, a and d go in. Setting a again should make d the oldest, so adding c evicts d. The buggy cache evicts a instead, and get(a) returns undefined where the model still has it. No fixed example list would have included “update an existing key, then fill the cache, then read the updated key”. Deleting the key before setting it (this.m.delete(k) ahead of this.m.set(k, v)) fixes it, and the test then passes.

Keep the model dumb. If it needs cleverness, it will have its own bugs, and you will spend the time debugging the test.

Practical advice

  • Constrain generators instead of filtering. fc.integer({ min: 1, max: 20 }) is better than fc.integer().filter(n => n > 0), which wastes inputs and shrinks worse. fc.uniqueArray gives lists without duplicates.
  • Keep properties fast. One hundred runs of a test that takes 50 ms is five seconds. Expensive properties belong in a nightly job with a high numRuns, not in the watch loop.
  • Run them in CI with the seed logged. The failure message already prints it. Make sure your CI output keeps it, or a failure that appears once cannot be reproduced.
  • Start small. Add one property for one function that has bitten you before, such as money, dates, pagination or parsing. You do not need to convert a test suite.

The same habit carries over to Solidity: our invariant testing walkthrough uses the same sequence-of-calls idea inside Foundry, and when a shrunk failure turns out to be a regression, keep it as the check script for git bisect run.

If you have a service where the failures only show up in odd combinations of calls, we can help you build the tests that find them; see our backend development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open