Inject clocks, randomness, and ID generators
Pass a Clock, RandomSource, and IDGenerator into the unit that makes decisions, while production constructors supply real implementations. Tests can then cross boundaries and exhaust sequences without changing process-wide globals. Node.js test runner mock timers documents controlling time in Node.js tests.
Reproduce retries, collisions, and expiry boundaries
A retry test advances a virtual clock through backoff and deadline. An ID test returns a collision then a unique value to prove retry behavior. A month-end expiry test fixes wall time and zone explicitly. Seeded pseudo-randomness is useful for reproducibility, not security. RFC 9562: UUIDs defines the UUID formats these tests exercise.
Inject sources, not predetermined answers
Give production code small clock, random-byte, and identifier interfaces. Tests can supply a fixed instant, a seeded byte stream, or a sequence of IDs, while production adapters use the platform implementations. Keep the seam narrow: business code should ask for now or random bytes, not control timer internals.
A UUID test should assert version, variant, uniqueness behavior, and propagation rather than one memorized production value. A retry test should advance a fake clock and verify the schedule without sleeping. Each test owns its fake; a global clock changed by parallel tests creates a new form of nondeterminism.
Preserve integration confidence
Deterministic unit tests cannot prove that real entropy, timer wiring, or time-zone data is configured correctly. Keep focused integration tests that use the production adapters and assert properties rather than exact values. Run concurrency cases with controlled barriers so the intended interleaving is reproducible.
Search the slowest flaky tests for sleeps, current-time reads, random IDs, and unordered collection comparisons. Replace one hidden dependency at a time. The useful finish line is a failure that reproduces with a recorded seed or clock sequence, while production still receives cryptographically appropriate randomness where security requires it.
Sources are linked throughout this guide. Product capabilities can change; consult the linked documentation for your deployment.
Read our editorial approach ↗