Skip to content

Property-Based Testing

In one line

Property-based testing checks universal properties with random inputs — instead of testing specific cases, you test that rules always hold.

In simple words

Property-based testing flips traditional testing on its head. Instead of writing specific examples (test add(2, 3) === 5), you state general properties that should always hold, and the framework tests them with hundreds of random inputs.

Example properties:

  • Commutativity: add(a, b) === add(b, a) for all a, b
  • Identity: add(a, 0) === a for all a
  • Associativity: add(add(a, b), c) === add(a, add(b, c))
  • No crash: sort(array) never throws for any array
  • Idempotency: sort(sort(array)) === sort(array)

The framework generates random inputs, runs your code, and checks the property. If it finds a counterexample, it "shrinks" it to the simplest failing case (e.g., finding that add(-1, 0) fails instead of add(-847293, 0)).

Tools: fast-check (JS/TS), Hypothesis (Python), QuickCheck (Haskell), jqwik (Java).

Example

javascript
import fc from 'fast-check';

// Example-based test (only tests one case)
test('add(2, 3) = 5', () => {
  expect(add(2, 3)).toBe(5);
});

// Property-based test (tests 100+ random cases)
test('addition is commutative', () => {
  fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
    return add(a, b) === add(b, a);
  }));
});

test('addition identity: a + 0 = a', () => {
  fc.assert(fc.property(fc.integer(), (a) => {
    return add(a, 0) === a;
  }));
});

// If a counterexample is found, fast-check shrinks it:
// "Failed after 42 tests with [-847, 0]"
// Shrunk: "Failed with [-1, 0]" (simplest failing case)

Instead of specific examples, you state properties (rules) and the framework tests them with random inputs. Counterexamples are shrunk to minimal failing cases.

Common confusions

  • Confused with: fuzz testing

    The difference: Property-based testing checks that specific properties/invariants hold for random inputs — it has assertions. Fuzz testing just feeds random/malformed inputs to see if the program crashes — it checks for crashes, not correctness. Property-based testing is more precise; fuzz testing is more exploratory.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary