~/qa-guides/property-based-testing
>_ Property-Based Testing: Generators, Invariants, and Shrinking
A checkout loses a cent when it splits 10 cents three ways. A saved filter turns one tag into two. Build generators to find and replay both failures in JavaScript.
Short answer
Property-based testing checks a rule against many generated inputs. A generator describes the values a feature accepts. A property states what must hold when the feature processes those values. A failing input is a counterexample. Shrinking tries simpler inputs and keeps the ones that still demonstrate a failure. The result gives you a concrete case to debug and save.
Suppose a checkout splits 12 cents between three people and returns [4, 4, 4]. That example passes. What should hold for every split? All the cents must reach the recipients. For 10 cents, [3, 3, 3] accounts for only nine. A test can detect the missing cent without calculating each person's expected share.
Derive an invariant from the splitting rule
For this exercise, the checkout accepts an integer amount from 0 to 100 cents and a recipient count from 1 to 8. It returns one nonnegative integer per recipient, in the original recipient order. Shares may differ by at most one cent. Hand out leftover cents in recipient order, at most one extra cent each. Zero cents is a valid amount and produces a zero share for everyone.
The first invariant is conservation. Add up the returned shares and compare the sum with the input amount. That calculation is independent of the allocator's rounding code. It can catch a missing cent even if the test author has never seen the combination of amount and recipient count that lost it.
The generator needs to vary those two inputs independently. Generating a complete checkout record would add names, IDs, and other values that cannot affect this calculation. For a test that really does depend on an account, a currency, or a saved order, the test data design guide shows how to establish that starting state.
Write a property-based test with fast-check
The examples ran on Node.js 22.22.2 with fast-check 4.11.0. In an empty directory, run npm install --save-exact fast-check@4.11.0. Put the following lines, in order, in split.test.mjs. The function under test deliberately rounds down every share. In a checkout project, this is where you would import the allocator the application calls.
import * as fc from 'fast-check'const cents = fc.integer({ min: 0, max: 100 })const people = fc.integer({ min: 1, max: 8 })const split = (amount, n) => Array(n).fill(Math.floor(amount / n))const sum = shares => shares.reduce((a, b) => a + b, 0)const conserves = fc.property(cents, people, (amount, n) => sum(split(amount, n)) === amount)const options = { seed: 42, numRuns: 100, verbose: true }const report = fc.check(conserves, options)console.log(report.failures, report.counterexample, report.counterexamplePath)
Run node split.test.mjs. In fast-check, a generator with instructions for simplifying its values is called an arbitrary. The two integer arbitraries here supply arguments to the property. The predicate gets ordinary numbers, calls the allocator, and returns a boolean. The fixed seed makes this particular experiment repeatable. How fast-check generates inputs and shrinks failures
Use fc.check when you want to inspect the report, as this script does. A failed property is returned as data, so printing it alone can leave the process with a successful exit status. In a test suite, fc.assert(conserves) throws on failure and lets the test runner report it.
Read the counterexample and replay the failure
The first generated pair was [96, 3]. All three recipients got 32 cents. The second pair, [24, 7], produced seven shares of three cents. The expected total was 24 and the actual total was 21. At that point fast-check started shrinking. The budget of 100 did not require it to continue generating unrelated checkouts after the failure.
The verbose report lists the failing candidates it kept. With seven recipients, the amounts went from 24 to 12, 6, 3, 2, and 1. With the amount at one cent, the recipient count fell from 7 to 4, then 3, then 2. Testing zero cents or a single recipient made this defect disappear. The report recorded eight successful shrink steps and the final arguments [1, 2]. The corresponding output, [0, 0], is enough to explain what a shopper lost.
To jump directly to that case, append these two lines to the same file and run it again.
const replay = { seed: 42, path: '1:1:0:0:0:0:2:1:1', endOnFailure: true }console.log(fc.check(conserves, replay).counterexample)
The seed reconstructs the generated sequence. The path identifies the case reached during shrinking. Keep the library version, generator definitions, and their argument order with the report. A change such as swapping the two generators changes how the same sequence is interpreted. Keep the literal failing values too, so someone investigating a later revision can call the allocator directly. How to read and replay a fast-check report
A second run illustrates the limit of the word "smallest." With seed: 17, the first failure was [3, 2]. The shrinker tried [0, 2], [2, 2], and [3, 1]. Each conserved the total, so the report kept [3, 2] with zero successful shrinks. Both seeds found the same rounding bug. Only one of these runs reached the one-cent example.
Check what a green result would let through
Conservation alone allows a checkout to put all 10 cents into the first pocket. For an input of 10 cents and three recipients, these four implementations produce different results. All four return the requested number of whole, nonnegative shares.
| Shares | Sum | Verdict |
|---|---|---|
[3, 3, 3] | 9 | One cent lost |
[10, 0, 0] | 10 | Shares too far apart |
[3, 3, 4] | 10 | Extra cent goes last |
[4, 3, 3] | 10 | All rules hold |
Validate the shape with shares.length === n and shares.every(s => Number.isInteger(s) && s >= 0). Check the balance using Math.max(...shares) - Math.min(...shares) <= 1. For the tie rule, use shares.every((s, i) => i === 0 || shares[i - 1] >= s). Together with conservation, these assertions distinguish all four rows. Teams with a different policy for leftover cents can change the order assertion to match their agreement with users.
To repair the example, replace the original split declaration with these two lines before creating conserves. The quotient gives every recipient a base share. The remainder counts how many recipients need one more cent.
const shareAt = (amount, n, i) => Math.floor(amount / n) + Number(i < amount % n)const split = (amount, n) => Array.from({ length: n }, (_, i) => shareAt(amount, n, i))
The reduced case now gives [1, 0]. Check that exact output in a regression test. Remove the replay lines and rerun the original property on the repaired function. With the same seed it completes all 100 cases. For this small domain we also checked every one of the 808 possible argument pairs against all four requirements for shape, total, balance, and order. The repaired allocator passed every pair. The original lost cents on 530 of them.
A generator that hides a bug
Suppose the fixture starts with a per-person charge and derives the total by multiplying it by the group size. Generate a charge from 0 to 12 cents and a group size from 1 to 8. Every resulting total divides evenly. The original, broken allocator passed 100 generated cases with seed 42 under this arrangement. Increasing the run budget preserves that blind spot.
To exercise the remainder branch deliberately, pick a recipient count of at least two, a base share from 0 to 11, and a remainder from one to one less than the count. Build the total as base * count + remainder. With a count of four, a base of two and a remainder of three, the input becomes 11 cents for four people. Keep exact divisions and zero amounts in other cases. Each part of the generator now has a reason to exist.
A different property could increase the total by one cent per recipient and check that every share increases by one. The original floor-only implementation actually satisfies that relation whenever both totals fit the domain. The metamorphic testing guide explains how to choose an informative comparison between related executions.
Round-trip a saved list of tags
A saved filter stores an ordered list of tags. An empty list is valid, repeated tags must survive, and sales,eu is one valid tag. The property is a round trip. Reading a newly written list should return the same strings in the same order. You can state the expected result directly from the input, even when you do not know which list the generator will choose.
Create a second file, tags.test.mjs, in the same directory. This first version uses a comma as the storage separator. The short vocabulary gives the generator ordinary tags and a tag containing the separator. It can vary their order, repeat them, or choose none.
import * as fc from 'fast-check'import assert from 'node:assert/strict'const vocabulary = fc.constantFrom('sales', 'eu', 'sales,eu')const labels = fc.array(vocabulary, { maxLength: 5 })const encode = xs => xs.join(',')const decode = text => text === '' ? [] : text.split(',')const roundTrip = fc.property(labels, xs => assert.deepEqual(decode(encode(xs)), xs))const result = fc.check(roundTrip, { seed: 42, numRuns: 100, verbose: true })console.log(result.counterexample, result.counterexamplePath)
Run node tags.test.mjs. The first failing list had four entries. Two successful shrinks left just ["sales,eu"]. The actual read returned ["sales", "eu"]. The report displays [["sales,eu"]] because this property takes one argument and the argument itself is a list. Its replay path is 1:2:2.
For a new storage format, replace the encoder with const encode = xs => JSON.stringify(xs) and the decoder with const decode = text => JSON.parse(text). The same 100-case run passed. There is a separate question for previously stored filters. A legacy value of sales,eu could have come from either of the two lists above. Their bytes are identical. Before a migration, use an independent record of the original selection or define how the product should handle the ambiguity. A round trip through the new writer cannot recover that lost distinction.
FAQ
Measure how long the property takes and identify the input combinations that matter to the feature. A fast allocation check can afford a wider run than a test that saves and reloads a filter through a database. Give a rare but essential branch an explicit example or a dedicated generator. A count of completed runs alone tells you little about whether that branch executed.
Give rejection its own property once the product defines the behavior. If the checkout rejects zero recipients, generate amounts with the count fixed at zero and assert the specified error. A caller that persists shares should also leave the original record intact. Keeping that test separate makes it possible to tell a correct rejection from a cent lost on a valid checkout.
Call the function twice with the literal counterexample and the same starting state. Check whether the first call mutated the array or a stored filter, or whether the test reads a clock or another source of randomness. The seed controls values drawn by fast-check. Restore each external dependency before using the sequence of shrinks to diagnose a product defect.