Testing Race Conditions and Timing
You'll learn how to reliably test code that depends on timing or simultaneous operations without flaky tests.
The Challenge of Time-Dependent Tests
When your code involves timeouts, intervals, or operations that fire at specific moments, writing tests becomes tricky. Real timers make tests slow and unpredictable—a setTimeout(fn, 5000) forces your test to wait 5 full seconds. Worse, timing-dependent logic can behave differently on slow CI servers versus your local machine, creating "flaky" tests that pass sometimes and fail others.
Think of it like testing a traffic light controller: you don't want to wait actual minutes for the light cycle. Instead, you need a way to "fast-forward time" on demand.
Fake Timers to the Rescue
Modern test runners provide fake timers (sometimes called "mock timers") that replace JavaScript's native setTimeout, setInterval, and Date.now() with controllable versions. You can advance time instantly, making tests fast and deterministic.
import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert';
describe('Debounced function', () => {
beforeEach(() => {
// Enable fake timers
global.clock = { now: 0 };
});
it('should only execute after the delay period', () => {
let callCount = 0;
const debounced = debounce(() => callCount++, 1000);
debounced();
debounced();
debounced();
// Advance time by 999ms - function shouldn't fire yet
advanceTimersByTime(999);
assert.strictEqual(callCount, 0);
// Advance 1 more ms - now it fires
advanceTimersByTime(1);
assert.strictEqual(callCount, 1);
});
});
Controlled Delays for Race Conditions
For race conditions (when order of async operations matters), use controlled delays or Promise resolution ordering. You orchestrate exactly when each operation completes, ensuring consistent test behavior.
Key Takeaway: Use fake timers to control time-dependent code in tests, making them fast, predictable, and immune to system performance variations—essential for testing debouncing, throttling, polling, and race conditions.