fast-check
Overview
fast-check is a property-based testing framework — instead of writing specific test cases, you describe properties that should always hold, and fast-check generates thousands of random inputs to try to break them. When it finds a failing input, it automatically shrinks it to the minimal reproducing case. Catches edge cases you'd never think to test: empty strings, negative numbers, Unicode, massive arrays, boundary values.
When to Use
- Functions with many possible inputs (parsers, validators, serializers)
- Finding edge cases in business logic (pricing, permissions, date handling)
- Testing serialization/deserialization roundtrips (encode → decode = original)
- Verifying mathematical properties (commutativity, associativity)
- Replacing hand-written test cases with generated ones
Instructions
Setup
npm install -D fast-check
Basic Properties
// math.test.ts — Property-based testing for math functions
import fc from "fast-check";
import { describe, it, expect } from "vitest";
describe("sort", () => {
it("should produce an array of same length", () => {
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
const sorted = [...arr].sort((a, b) => a - b);
return sorted.length === arr.length;
})
);
});
it("should produce ordered output", () => {
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
const sorted = [...arr].sort((a, b) => a - b);
for (let i = 1; i < sorted.length; i++) {
expect(sorted[i]).toBeGreaterThanOrEqual(sorted[i - 1]);
}
})
);
});
it("should contain the same elements", () => {
fc.assert(
fc.property(fc.array(fc.integer()), (arr) => {
const sorted = [...arr].sort((a, b) => a - b);
expect(sorted).toEqual(expect.arrayContaining(arr));
expect(arr).toEqual(expect.arrayContaining(sorted));
})
);
});
});
Roundtrip Testing
// serialization.test.ts — Encode/decode roundtrips
import fc from "fast-check";
import { encode, decode } from "./my-codec";
it("decode(encode(x)) === x for any string", () => {
fc.assert(
fc.property(fc.string(), (original) => {
const encoded = encode(original);
const decoded = decode(encoded);
expect(decoded).toEqual(original);
})
);
});
it("JSON roundtrip preserves data", () => {
fc.assert(
fc.property(fc.jsonValue(), (value) => {
const json = JSON.stringify(value);
const parsed = JSON.parse(json);
expect(parsed).toEqual(value);
})
);
});
Custom Arbitraries
// business.test.ts — Custom data generators for domain objects
import fc from "fast-check";
// Generate realistic user objects
const userArbitrary = fc.record({
id: fc.uuid(),
name: fc.string({ minLength: 1, maxLength: 100 }),
email: fc.emailAddress(),
age: fc.integer({ min: 13, max: 120 }),
role: fc.constantFrom("admin", "user", "viewer"),
createdAt: fc.date({ min: new Date("2020-01-01"), max: new Date() }),
});
// Generate realistic money amounts
const moneyArbitrary = fc.record({
amount: fc.integer({ min: 0, max: 1_000_000 }), // Cents
currency: fc.constantFrom("USD", "EUR", "GBP"),
});
it("discount should never result in negative price", () => {
fc.assert(
fc.property(
moneyArbitrary,
fc.integer({ min: 0, max: 100 }), // Discount percentage
(price, discountPercent) => {
const discounted = applyDiscount(price, discountPercent);
expect(discounted.amount).toBeGreaterThanOrEqual(0);
}
)
);
});
it("total should equal sum of line items", () => {
fc.assert(
fc.property(
fc.array(moneyArbitrary, { minLength: 1, maxLength: 50 }),
(items) => {
const total = calculateTotal(items);
const expected = items.reduce((sum, item) => sum + item.amount, 0);
expect(total).toBe(expected);
}
)
);
});
Shrinking (Automatic Minimal Reproduction)
// When a property fails, fast-check automatically finds the SMALLEST failing input
it("handles edge cases in URL parsing", () => {
fc.assert(
fc.property(fc.webUrl(), (url) => {
const parsed = parseUrl(url);
expect(parsed.protocol).toBeTruthy();
// If this fails on a complex URL, fast-check shrinks it to
// the simplest URL that still fails, e.g., "http://a"
})
);
});
Examples
Example 1: Test a parser for edge cases
User prompt: "My CSV parser breaks on weird inputs. Find all the edge cases."
The agent will write properties like "parse(serialize(data)) === data", generate random CSV data with edge cases (commas in fields, newlines, empty cells, Unicode), and identify failing inputs.
Example 2: Verify pricing logic
User prompt: "Test our discount calculation to make sure it never produces negative prices or rounding errors."
The agent will generate random prices, discount percentages, and coupon combinations, then verify invariants (non-negative, correct rounding, order doesn't matter).
Guidelines
- Think in properties, not examples — "sorted output is ordered" not "sort([3,1,2]) = [1,2,3]"
- Roundtrip is the easiest property —
decode(encode(x)) === x
fc.assert runs 100 iterations by default — increase with { numRuns: 1000 }
- Shrinking is automatic — failed inputs are minimized to the simplest case
- Built-in arbitraries cover most needs —
string, integer, array, record, date, uuid, emailAddress
constantFrom for enums — fc.constantFrom("a", "b", "c")
fc.pre(condition) for preconditions — skip inputs that don't meet criteria
- Combine with example-based tests — properties find unknowns, examples verify knowns
- Seed for reproducibility — failed runs print a seed; re-run with same seed to reproduce
1---2name: fast-check3description: >-4 Find edge-case bugs with property-based testing using fast-check — generate5 thousands of random inputs automatically. Use when someone asks to "find6 edge cases", "fast-check", "property-based testing", "fuzz testing in7 TypeScript", "generate random test data", "QuickCheck for JavaScript",8 or "test with random inputs". Covers property definitions, arbitraries,9 shrinking, model-based testing, and integration with Vitest/Jest.10license: Apache-2.011compatibility: "TypeScript/JavaScript. Vitest, Jest, Mocha, or standalone."12metadata:13 source: https://skillmd.com/skills/eliferjunior/fast-check14 author: terminal-skills15 version: "1.0.0"16 category: development17 tags: ["testing", "property-based", "fast-check", "fuzzing", "edge-cases"]18---1920# fast-check2122## Overview2324fast-check is a property-based testing framework — instead of writing specific test cases, you describe properties that should always hold, and fast-check generates thousands of random inputs to try to break them. When it finds a failing input, it automatically shrinks it to the minimal reproducing case. Catches edge cases you'd never think to test: empty strings, negative numbers, Unicode, massive arrays, boundary values.2526## When to Use2728- Functions with many possible inputs (parsers, validators, serializers)29- Finding edge cases in business logic (pricing, permissions, date handling)30- Testing serialization/deserialization roundtrips (encode → decode = original)31- Verifying mathematical properties (commutativity, associativity)32- Replacing hand-written test cases with generated ones3334## Instructions3536### Setup3738```bash39npm install -D fast-check40```4142### Basic Properties4344```typescript45// math.test.ts — Property-based testing for math functions46import fc from "fast-check";47import { describe, it, expect } from "vitest";4849describe("sort", () => {50 it("should produce an array of same length", () => {51 fc.assert(52 fc.property(fc.array(fc.integer()), (arr) => {53 const sorted = [...arr].sort((a, b) => a - b);54 return sorted.length === arr.length;55 })56 );57 });5859 it("should produce ordered output", () => {60 fc.assert(61 fc.property(fc.array(fc.integer()), (arr) => {62 const sorted = [...arr].sort((a, b) => a - b);63 for (let i = 1; i < sorted.length; i++) {64 expect(sorted[i]).toBeGreaterThanOrEqual(sorted[i - 1]);65 }66 })67 );68 });6970 it("should contain the same elements", () => {71 fc.assert(72 fc.property(fc.array(fc.integer()), (arr) => {73 const sorted = [...arr].sort((a, b) => a - b);74 expect(sorted).toEqual(expect.arrayContaining(arr));75 expect(arr).toEqual(expect.arrayContaining(sorted));76 })77 );78 });79});80```8182### Roundtrip Testing8384```typescript85// serialization.test.ts — Encode/decode roundtrips86import fc from "fast-check";87import { encode, decode } from "./my-codec";8889it("decode(encode(x)) === x for any string", () => {90 fc.assert(91 fc.property(fc.string(), (original) => {92 const encoded = encode(original);93 const decoded = decode(encoded);94 expect(decoded).toEqual(original);95 })96 );97});9899it("JSON roundtrip preserves data", () => {100 fc.assert(101 fc.property(fc.jsonValue(), (value) => {102 const json = JSON.stringify(value);103 const parsed = JSON.parse(json);104 expect(parsed).toEqual(value);105 })106 );107});108```109110### Custom Arbitraries111112```typescript113// business.test.ts — Custom data generators for domain objects114import fc from "fast-check";115116// Generate realistic user objects117const userArbitrary = fc.record({118 id: fc.uuid(),119 name: fc.string({ minLength: 1, maxLength: 100 }),120 email: fc.emailAddress(),121 age: fc.integer({ min: 13, max: 120 }),122 role: fc.constantFrom("admin", "user", "viewer"),123 createdAt: fc.date({ min: new Date("2020-01-01"), max: new Date() }),124});125126// Generate realistic money amounts127const moneyArbitrary = fc.record({128 amount: fc.integer({ min: 0, max: 1_000_000 }), // Cents129 currency: fc.constantFrom("USD", "EUR", "GBP"),130});131132it("discount should never result in negative price", () => {133 fc.assert(134 fc.property(135 moneyArbitrary,136 fc.integer({ min: 0, max: 100 }), // Discount percentage137 (price, discountPercent) => {138 const discounted = applyDiscount(price, discountPercent);139 expect(discounted.amount).toBeGreaterThanOrEqual(0);140 }141 )142 );143});144145it("total should equal sum of line items", () => {146 fc.assert(147 fc.property(148 fc.array(moneyArbitrary, { minLength: 1, maxLength: 50 }),149 (items) => {150 const total = calculateTotal(items);151 const expected = items.reduce((sum, item) => sum + item.amount, 0);152 expect(total).toBe(expected);153 }154 )155 );156});157```158159### Shrinking (Automatic Minimal Reproduction)160161```typescript162// When a property fails, fast-check automatically finds the SMALLEST failing input163164it("handles edge cases in URL parsing", () => {165 fc.assert(166 fc.property(fc.webUrl(), (url) => {167 const parsed = parseUrl(url);168 expect(parsed.protocol).toBeTruthy();169 // If this fails on a complex URL, fast-check shrinks it to170 // the simplest URL that still fails, e.g., "http://a"171 })172 );173});174```175176## Examples177178### Example 1: Test a parser for edge cases179180**User prompt:** "My CSV parser breaks on weird inputs. Find all the edge cases."181182The agent will write properties like "parse(serialize(data)) === data", generate random CSV data with edge cases (commas in fields, newlines, empty cells, Unicode), and identify failing inputs.183184### Example 2: Verify pricing logic185186**User prompt:** "Test our discount calculation to make sure it never produces negative prices or rounding errors."187188The agent will generate random prices, discount percentages, and coupon combinations, then verify invariants (non-negative, correct rounding, order doesn't matter).189190## Guidelines191192- **Think in properties, not examples** — "sorted output is ordered" not "sort([3,1,2]) = [1,2,3]"193- **Roundtrip is the easiest property** — `decode(encode(x)) === x`194- **`fc.assert` runs 100 iterations by default** — increase with `{ numRuns: 1000 }`195- **Shrinking is automatic** — failed inputs are minimized to the simplest case196- **Built-in arbitraries cover most needs** — `string`, `integer`, `array`, `record`, `date`, `uuid`, `emailAddress`197- **`constantFrom` for enums** — `fc.constantFrom("a", "b", "c")`198- **`fc.pre(condition)` for preconditions** — skip inputs that don't meet criteria199- **Combine with example-based tests** — properties find unknowns, examples verify knowns200- **Seed for reproducibility** — failed runs print a seed; re-run with same seed to reproduce