Testing and QA · Intermediate · 24 min
Write property-based tests in TypeScript with fast-check
By Padding · Updated 18 Nov 2026
Node.js 26.13 · fast-check 4.11.0 · Vitest 5.1.1 · checked on node:26
You will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
On this page
An example-based test checks the inputs you thought of. A property-based test states a rule that must hold for every input, then lets a library generate hundreds of inputs and try to break it. When one breaks the rule, the library shrinks it down to the smallest input that still fails, so the report reads like a bug you could have written by hand.
fast-check is the property-based testing library for JavaScript and TypeScript. It works inside any test runner; here you use Vitest, which runs .ts files directly with no build step.
You build a small money module of the kind found in any checkout or bill-splitting app. Amounts are whole minor units (kobo, cents, pence), so 1000 means 10.00. The module has a rounding bug that two example tests miss. A property finds it in well under a second. You then replay that exact failure from its seed, fix the bug, write properties for a formatter and parser, and finish by testing a shopping cart against a simple model using generated sequences of actions.
Step 1 · Set up the project
Make a throwaway folder, start a package and install Vitest and fast-check as development dependencies. Both are pinned so your output matches this tutorial:
mkdir -p ~/fast-check-demo
cd ~/fast-check-demo
npm init -y > /dev/null
npm pkg set type=module
npm pkg set "scripts.test=vitest run"
npm install --save-dev vitest@5.1.1 fast-check@4.11.0
mkdir -p src test
npx vitest --versionvitest run runs the suite once and exits, which is what you want in CI and in this tutorial. Plain npx vitest starts watch mode instead, rerunning tests as you save.
Vitest strips TypeScript types as it loads files, but it does not type-check them. If you want tsc checking too, set up a project as in the TypeScript tutorial linked at the end; nothing here depends on it.
Check it worked
npx vitest --version prints a line starting vitest/5.1.1. package.json lists fast-check and vitest under devDependencies.
Step 2 · Write a money module and an example test
splitEvenly shares a total between a number of people, as when friends split a restaurant bill or a group contribution is divided between members. Write it the obvious way, with Math.round:
cd ~/fast-check-demo
cat > src/money.ts <<'TS'
// Amounts are integers in minor units: 1000 means 10.00.
export function splitEvenly(totalMinor: number, parts: number): number[] {
if (!Number.isSafeInteger(totalMinor) || totalMinor < 0) {
throw new RangeError(`totalMinor must be a whole number of 0 or more, got ${totalMinor}`);
}
if (!Number.isInteger(parts) || parts < 1) {
throw new RangeError(`parts must be a whole number of 1 or more, got ${parts}`);
}
const share = Math.round(totalMinor / parts);
return Array.from({ length: parts }, () => share);
}
TS
cat > test/money.test.ts <<'TS'
import { describe, expect, test } from 'vitest';
import { splitEvenly } from '../src/money';
describe('splitEvenly', () => {
test('splits 10.00 four ways', () => {
expect(splitEvenly(1000, 4)).toEqual([250, 250, 250, 250]);
});
test('splits 90.00 three ways', () => {
expect(splitEvenly(9000, 3)).toEqual([3000, 3000, 3000]);
});
});
TS
npx vitest runBoth examples pass. They also share a blind spot: each total divides exactly. Whoever wrote them picked tidy numbers, which is what people do.
Check it worked
The output ends with a summary showing 1 passed for test files and 2 passed for tests.
Step 3 · State the rule as a property
What must be true of any split, whatever the numbers? Two things a customer would complain about if they broke:
- The shares add up to the total. Nobody pays more, and no money goes missing.
- No two shares differ by more than one minor unit.
Write those as a property. fc.integer describes the inputs (an arbitrary, in fast-check's terms), fc.property joins the arbitraries to a function that checks the rule, and fc.assert runs it 100 times with fresh inputs and throws if any run fails:
cd ~/fast-check-demo
cat > test/split.property.test.ts <<'TS'
import fc from 'fast-check';
import { expect, test } from 'vitest';
import { splitEvenly } from '../src/money';
const total = fc.integer({ min: 0, max: 10_000_000 });
const people = fc.integer({ min: 1, max: 12 });
test('shares add up to the total and differ by at most 1', () => {
fc.assert(
fc.property(total, people, (totalMinor, parts) => {
const shares = splitEvenly(totalMinor, parts);
expect(shares).toHaveLength(parts);
expect(shares.reduce((sum, s) => sum + s, 0)).toBe(totalMinor);
expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(1);
}),
);
});
TSThe checking function can use expect, as here, or return true or false. Either way, a thrown error or a false counts as a failure.
Run the suite. It fails, so the exit code is not zero:
cd ~/fast-check-demo
npx vitest run 2>&1 | tee first-run.txtRead the error from the top. You see something like this (your numbers will differ):
Error: Property failed after 1 tests
{ seed: 1748392011, path: "0:1:0:0:2", endOnFailure: true }
Counterexample: [1,2]
Shrunk 9 time(s)Property failed after 1 tests: the first generated input already broke the rule.seedandpathidentify that run, so it can be repeated exactly. You use them in the next step.Counterexample: [1,2]is the input after shrinking: a total of 1 split between 2 people.Math.round(0.5)is 1, so both people pay 1 and the shares add up to 2.Shrunk 9 time(s)means the first failing input was something large and untidy, such as 4,718,203 split 7 ways, and fast-check cut it down step by step while it kept failing.
Below that, Vitest shows the expect message that failed, with the expected total and the sum it got.
Check it worked
The output contains Property failed after, a line with seed: and path:, and a Counterexample: with two small numbers. The two example tests still pass; only the property fails.
Step 4 · Replay the failure, then fix the bug
A property run uses a new random seed each time, so a failure you saw once can be hard to see again. Passing the reported seed and path back to fc.assert replays that run and goes straight to the shrunk counterexample. Copying them into the test file by hand works, but it is easy to commit by mistake. A small helper that reads them from environment variables keeps the test file clean:
cd ~/fast-check-demo
cat > test/replay.ts <<'TS'
// Set FC_SEED and FC_PATH from a failure report to replay that exact run.
export function replay() {
const seed = process.env.FC_SEED;
if (!seed) return {};
return { seed: Number(seed), path: process.env.FC_PATH, endOnFailure: true };
}
TS
cat > test/split.property.test.ts <<'TS'
import fc from 'fast-check';
import { expect, test } from 'vitest';
import { splitEvenly } from '../src/money';
import { replay } from './replay';
const total = fc.integer({ min: 0, max: 10_000_000 });
const people = fc.integer({ min: 1, max: 12 });
test('shares add up to the total and differ by at most 1', () => {
fc.assert(
fc.property(total, people, (totalMinor, parts) => {
const shares = splitEvenly(totalMinor, parts);
expect(shares).toHaveLength(parts);
expect(shares.reduce((sum, s) => sum + s, 0)).toBe(totalMinor);
expect(Math.max(...shares) - Math.min(...shares)).toBeLessThanOrEqual(1);
}),
replay(),
);
});
TSNow replay. Replace <seed> and <path> with the values from your own failure report, keeping the quotes around the path:
cd ~/fast-check-demo
FC_SEED=<seed> FC_PATH="<path>" npx vitest run test/split.property.test.tsThe replay fails straight away with the same counterexample, without searching or shrinking again. This is what you would attach to a bug report, or paste into a colleague's terminal.
Now the fix. Give everyone the rounded-down share, then hand the leftover minor units out one each to the first people in the list. The total is preserved exactly and shares differ by at most one:
cd ~/fast-check-demo
cat > src/money.ts <<'TS'
// Amounts are integers in minor units: 1000 means 10.00.
export function splitEvenly(totalMinor: number, parts: number): number[] {
if (!Number.isSafeInteger(totalMinor) || totalMinor < 0) {
throw new RangeError(`totalMinor must be a whole number of 0 or more, got ${totalMinor}`);
}
if (!Number.isInteger(parts) || parts < 1) {
throw new RangeError(`parts must be a whole number of 1 or more, got ${parts}`);
}
const base = Math.floor(totalMinor / parts);
const leftover = totalMinor % parts;
return Array.from({ length: parts }, (_, i) => (i < leftover ? base + 1 : base));
}
TS
npx vitest runWho gets the extra unit is a business decision (the payer, the first name, the largest order). The property does not care, which is the point: it states what must always be true and leaves the policy to the code.
Check it worked
The replay command fails with the same Counterexample: line as your first run. After the fix, npx vitest run passes: 2 passed test files and 3 passed tests.
Step 5 · Build richer inputs with arbitraries
Properties shine wherever two pieces of code should undo each other, such as a serialiser and its parser, or wherever a rule should hold however the input is cut up. Add a formatter, a parser and an order total to the money module. Each new file in this step is written in full:
cd ~/fast-check-demo
cat > src/format.ts <<'TS'
// Text form of an amount: "-12.05" for -1205. Always two decimal places.
export function formatMinor(minor: number): string {
const sign = minor < 0 ? '-' : '';
const abs = Math.abs(minor);
const whole = Math.floor(abs / 100);
const fraction = String(abs % 100).padStart(2, '0');
return `${sign}${whole}.${fraction}`;
}
// Returns null for anything that is not exactly the format above.
export function parseMinor(text: string): number | null {
const match = /^(-?)(\d+)\.(\d{2})$/.exec(text);
if (!match) return null;
const value = Number(match[2]) * 100 + Number(match[3]);
if (!Number.isSafeInteger(value)) return null;
return match[1] === '-' ? 0 - value : value;
}
export type Line = { sku: string; qty: number; unitMinor: number };
export function orderTotal(lines: Line[]): number {
return lines.reduce((sum, line) => sum + line.qty * line.unitMinor, 0);
}
TS
cat > test/format.property.test.ts <<'TS'
import fc from 'fast-check';
import { expect, test } from 'vitest';
import { formatMinor, orderTotal, parseMinor } from '../src/format';
const amount = fc.integer({ min: -1_000_000_000_000, max: 1_000_000_000_000 });
test('parse undoes format', () => {
fc.assert(
fc.property(amount, (minor) => {
expect(parseMinor(formatMinor(minor))).toBe(minor);
}),
);
});
test('parse never throws and returns null or a whole number', () => {
const anyText = fc.oneof(
fc.string({ unit: 'grapheme', maxLength: 20 }),
amount.map(formatMinor),
fc.constantFrom('', '.', '1.', '.50', '1.5', '1.500', '1,50', ' 1.50', '--1.00'),
);
fc.assert(
fc.property(anyText, (text) => {
const result = parseMinor(text);
expect(result === null || Number.isSafeInteger(result)).toBe(true);
}),
);
});
const line = fc.record({
sku: fc.constantFrom('rice-5kg', 'tea-100', 'soap-bar'),
qty: fc.integer({ min: 1, max: 20 }),
unitMinor: fc.integer({ min: 1, max: 500_000 }),
});
test('the total of two baskets is the sum of their totals', () => {
fc.assert(
fc.property(fc.array(line, { maxLength: 15 }), fc.array(line, { maxLength: 15 }), (a, b) => {
expect(orderTotal([...a, ...b])).toBe(orderTotal(a) + orderTotal(b));
}),
);
});
TS
npx vitest run test/format.property.test.tsWhat each arbitrary does here:
fc.integer({ min, max })keeps amounts within the range your app accepts. fast-check leans towards edge values such as 0, -1 and the bounds, which is where off-by-one bugs live.fc.string({ unit: 'grapheme' })generates any printable Unicode text, including accented letters, emoji and non-Latin scripts. The default unit is printable ASCII only, which would never try₦1.50or Amharic digits. If your users type amounts in more than one language or keyboard layout, this is the unit to use..map(formatMinor)turns a generated number into valid formatted text, so the parser sees well-formed input as well as noise.fc.constantFrom(...)picks from a fixed list. Add the near misses you know about here; fast-check tries them alongside the random text.fc.oneof(...)chooses one of several arbitraries for each run.fc.recordbuilds an object with one arbitrary per field, andfc.array(line)builds lists of those objects, including the empty list.
The order-total property needs no expected value at all. It says only that splitting a basket in two does not change what the customer pays, which would catch, for example, a per-basket rounding step or a discount applied twice.
Check it worked
The command reports 3 passed. To see the parser property earn its place, change \d{2} to \d{1,2} in src/format.ts and rerun: parse undoes format still passes, but you have quietly started accepting 1.5. Put \d{2} back before moving on. That gap is a hint to add a property for the reverse direction if canonical text matters to you.
Step 6 · Test a shopping cart against a model
Some code is a state machine more than a function: a cart, a cache, a queue. The bugs hide in sequences, such as adding the same item twice or removing one that is not there. Model-based testing generates whole sequences of actions, runs each one against the real object and a deliberately simple model, and checks they agree after every step.
Here is a cart with a bug in add:
cd ~/fast-check-demo
cat > src/cart.ts <<'TS'
export const PRICES = { 'rice-5kg': 4800, 'tea-100': 1250, 'soap-bar': 650 } as const;
export type Sku = keyof typeof PRICES;
export class Cart {
private lines = new Map<Sku, number>();
add(sku: Sku, qty: number): void {
this.lines.set(sku, qty);
}
remove(sku: Sku): void {
this.lines.delete(sku);
}
itemCount(): number {
let count = 0;
for (const qty of this.lines.values()) count += qty;
return count;
}
totalMinor(): number {
let total = 0;
for (const [sku, qty] of this.lines) total += PRICES[sku] * qty;
return total;
}
}
TSThe model is a plain Map of quantities. Each command is a class with three methods: check says whether the command makes sense in the current model state, run applies it to both the model and the cart and compares them, and toString is how it appears in a failure report.
cd ~/fast-check-demo
cat > test/cart.model.test.ts <<'TS'
import fc from 'fast-check';
import { expect, test } from 'vitest';
import { Cart, PRICES, type Sku } from '../src/cart';
type Model = { qty: Map<Sku, number> };
function compare(model: Model, cart: Cart) {
let count = 0;
let total = 0;
for (const [sku, qty] of model.qty) {
count += qty;
total += PRICES[sku] * qty;
}
expect(cart.itemCount()).toBe(count);
expect(cart.totalMinor()).toBe(total);
}
class AddCommand implements fc.Command<Model, Cart> {
constructor(readonly sku: Sku, readonly qty: number) {}
check() {
return true;
}
run(model: Model, cart: Cart) {
cart.add(this.sku, this.qty);
model.qty.set(this.sku, (model.qty.get(this.sku) ?? 0) + this.qty);
compare(model, cart);
}
toString() {
return `add(${this.sku}, ${this.qty})`;
}
}
class RemoveCommand implements fc.Command<Model, Cart> {
constructor(readonly sku: Sku) {}
check(model: Readonly<Model>) {
return model.qty.has(this.sku);
}
run(model: Model, cart: Cart) {
cart.remove(this.sku);
model.qty.delete(this.sku);
compare(model, cart);
}
toString() {
return `remove(${this.sku})`;
}
}
const sku = fc.constantFrom(...(Object.keys(PRICES) as Sku[]));
const commands = [
fc.tuple(sku, fc.integer({ min: 1, max: 3 })).map(([s, q]) => new AddCommand(s, q)),
sku.map((s) => new RemoveCommand(s)),
];
test('the cart agrees with the model after every action', () => {
fc.assert(
fc.property(fc.commands(commands, { maxCommands: 30 }), (cmds) => {
fc.modelRun(() => ({ model: { qty: new Map() }, real: new Cart() }), cmds);
}),
);
});
TSRun it:
cd ~/fast-check-demo
npx vitest run test/cart.model.test.tsIt fails, and the shrunk counterexample is a short list of commands, something like [add(rice-5kg, 1),add(rice-5kg, 1)]. Adding the same item twice leaves one in the cart instead of two, because add replaces the quantity rather than adding to it. A hand-written test would only catch this if someone thought to add the same item twice; the generator tries it as a matter of course.
Fix add so it adds to whatever is already there:
cd ~/fast-check-demo
cat > src/cart.ts <<'TS'
export const PRICES = { 'rice-5kg': 4800, 'tea-100': 1250, 'soap-bar': 650 } as const;
export type Sku = keyof typeof PRICES;
export class Cart {
private lines = new Map<Sku, number>();
add(sku: Sku, qty: number): void {
this.lines.set(sku, (this.lines.get(sku) ?? 0) + qty);
}
remove(sku: Sku): void {
this.lines.delete(sku);
}
itemCount(): number {
let count = 0;
for (const qty of this.lines.values()) count += qty;
return count;
}
totalMinor(): number {
let total = 0;
for (const [sku, qty] of this.lines) total += PRICES[sku] * qty;
return total;
}
}
TS
npx vitest run test/cart.model.test.tsKeep the model dumber than the code it checks. If the model is as clever as the cart, it can share the cart's bugs.
Check it worked
Before the fix, the report shows a Counterexample: made of add(...) commands for the same item. After the fix, the test passes with 1 passed.
Step 7 · Tune the run count and decide where properties belong
100 runs per property is fast-check's default, a sensible balance for a test suite you run on every save. Before a release, or in a nightly CI job, more runs explore more inputs. fc.configureGlobal sets defaults for every fc.assert; put it in a Vitest setup file so one environment variable controls the whole suite:
cd ~/fast-check-demo
cat > test/fc-setup.ts <<'TS'
import fc from 'fast-check';
// FC_RUNS=2000 npm test runs every property 2000 times.
fc.configureGlobal({ numRuns: Number(process.env.FC_RUNS ?? 100) });
TS
cat > vitest.config.ts <<'TS'
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
setupFiles: ['./test/fc-setup.ts'],
},
});
TS
npm test
FC_RUNS=2000 npm testconfigureGlobal does not accept path, which is why replaying a single failure goes through the replay() helper you wrote, not the setup file.
Where properties pay for themselves most:
- Pairs that must undo each other: format and parse, encode and decode, save and load, serialise to JSON and back.
- Money and other arithmetic with rounding, where totals must be preserved and the bugs sit at awkward remainders.
- Parsers and validators fed untrusted text, where "never throws, always returns a clean answer" is a rule worth stating.
- Stateful objects with a simple model: carts, caches, rate limiters, undo stacks.
Keep example tests too. They document specific business cases ("a 10.00 bill split four ways is 2.50 each"), and they read better in a code review than a generated input does. A good suite has a few of each.
If your CI runners are small, or your team works on low-end laptops, leave the default at 100 and raise it only in the nightly job; 2000 runs of a slow property adds up.
Check it worked
Both npm test runs pass with 4 passed test files and 7 passed tests. The FC_RUNS=2000 run takes noticeably longer, which shows the setting reached every property.
When you are finished, remove the demo folder with rm -rf ~/fast-check-demo.
Next steps
- Find edge cases with property-based testing in Hypothesis applies the same ideas in Python, including stateful testing.
- Test UI code with Vitest and DOM Testing Library covers the rest of Vitest: user-like interactions, mocked
fetchand coverage. - Set up a TypeScript 7 project adds type checking with
tscalongside the tests. - Write unit tests that stay useful helps you choose which example tests to keep next to your properties.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
- Write Java unit tests with JUnit 6 and AssertJYou will test a small transfer-fee calculator with JUnit 6.1 and AssertJ 3.27, using display names, nested and parameterised tests, exception checks, soft assertions, a temporary folder and one Mockito mock, and finish with 18 passing tests from mvn test.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials