Custom Shrinking Functions
You'll learn how to write shrinking logic that respects your domain rules and produces truly minimal failing examples.
Why Custom Shrinking Matters
When a property test fails, the framework automatically shrinks the input to find a simpler counterexample. However, the default shrinking strategy only knows about primitive types—it might reduce [5, 3, 1] to [0, 0, 0] without understanding that your list must be sorted or contain distinct values.
A custom shrinker preserves domain-specific invariants while still simplifying the input. Think of it like a puzzle: you're trying to make the pieces smaller while keeping the picture intact.
The Core Idea
Default shrinking works generically:
- Numbers shrink toward zero
- Lists shrink by removing elements
- Strings shrink by dropping characters
But your domain objects have rules. A custom shrinker ensures that every shrunk candidate still follows those rules. For example:
- A sorted list shrinker removes elements but keeps the remainder sorted
- A valid email shrinker simplifies the local part but maintains the
@domainstructure - A date range shrinker narrows the window but ensures
start ≤ end
Writing a Custom Shrinker
You typically define a function that takes your complex input and yields progressively simpler versions that still satisfy your invariants. The framework tries each candidate until it finds the smallest one that still fails.
Without running code, imagine shrinking a non-empty sorted list: you'd remove one element at a time from either end, but never produce an empty list (violating "non-empty") or scramble the order (violating "sorted").
Key Takeaway: Custom shrinking functions preserve domain invariants during simplification, ensuring minimal counterexamples remain valid inputs—making failures easier to understand and debug.