How to Write Deterministic Tests with Fake Clocks
Make time-dependent tests deterministic: inject a clock, advance it explicitly, and assert debounce, timeout, and expiry without real waits.
On this page
Introduction
Time is a common source of flaky tests. A test that waits for a debounce, a timeout, or an expiry sleeps in real time, which is slow and depends on the machine: under load the sleep may be too short, on a fast machine it is wasted, and the test passes or fails for reasons unrelated to the code. A fake clock removes the wait: the test advances time by an exact amount and asserts the behavior that should occur at that amount.
This tutorial covers injecting a clock, advancing it explicitly, asserting the transition, and testing the boundaries. The examples use a fake clock in JavaScript, and the technique applies in any runtime where time and timers can be injected.
Inject the clock instead of using globals
The code that depends on time should read the current time and set timers through an injected clock, not through the global Date and setTimeout. A clock object exposes now, setTimeout, and clearTimeout, and the production version wraps the globals while the test version is a fake the test controls. Injecting it as a dependency, or reading it from one replaceable source, makes the time source swappable.
Refactor the time-dependent code to take the clock, even if it is a small change, because the alternative is to patch the globals in the test, which is more fragile and can leak into other tests. The injected clock is explicit: the code declares that it uses time, and the test declares what time it is. That clarity is half the benefit.
// production: wrap the real clock
export const realClock = {
now: () => Date.now(),
setTimeout: (fn, ms) => setTimeout(fn, ms),
clearTimeout: (id) => clearTimeout(id),
};
// code takes the clock, not the globals
export function createDebouncer(clock, fn, delay) {
let timer;
return () => {
if (timer) clock.clearTimeout(timer);
timer = clock.setTimeout(fn, delay);
};
}
Advance the fake clock explicitly
The test installs a fake clock, calls the code, and then advances the clock by a known amount to fire a timer. A debouncer called three times in quick succession and then advanced past its delay fires once; advanced less than the delay, it fires never. The test states the amount and asserts the count, so the behavior is checked exactly rather than by sleeping and hoping.
Advancing is synchronous: the fake clock runs the timers whose due time has passed, in order, when the test advances. This makes the test fast and deterministic, because no real time passes. For a timeout test, advance past the timeout and assert the timeout fired; for an expiry test, advance past the expiry and assert the value is gone.
import { describe, it, expect } from 'vitest';
import { createDebouncer } from './debounce';
function fakeClock() {
let now = 0;
const timers = [];
return {
now: () => now,
setTimeout: (fn, ms) => { const t = { at: now + ms, fn }; timers.push(t); return t; },
clearTimeout: (t) => { const i = timers.indexOf(t); if (i >= 0) timers.splice(i, 1); },
advance: (ms) => { now += ms; for (const t of [...timers].filter((x) => x.at <= now)) { t.fn(); } },
};
}
it('fires once after the debounce delay', () => {
const clock = fakeClock();
const calls = [];
const debounce = createDebouncer(clock, () => calls.push(1), 100);
debounce(); debounce(); debounce();
expect(calls.length).toBe(0); // nothing yet
clock.advance(100); // cross the delay
expect(calls.length).toBe(1); // fired exactly once
});
Test the boundaries around each deadline
Time logic usually has a comparison with a boundary, and off-by-one errors live there. Test just before, exactly at, and just after each threshold: a token that expires at t, a rate limit that resets at the window boundary, a lease that is valid up to an expiry. Advance to one tick before and assert the old behavior, to the boundary and assert the new, and one tick after and assert the new remains.
The exact-at case is the one people get wrong, because it depends on whether the comparison is inclusive. Write the test to state the intended behavior at the boundary, so the code matches it. If the requirement is ambiguous, decide it before writing the test, because the test will encode the decision either way.
it('expires exactly at the expiry time', () => {
const clock = fakeClock();
const cache = new TtlCache(clock, 1000);
cache.set('k', 'v');
clock.advance(999); expect(cache.get('k')).toBe('v'); // just before
clock.advance(1); expect(cache.get('k')).toBeUndefined(); // exactly at
clock.advance(1); expect(cache.get('k')).toBeUndefined(); // after
});
Keep real-time tests for the integration level
A fake clock is for unit tests of the time logic. Some behavior depends on real time in a way a fake cannot capture: the OS timer resolution, the event loop’s actual scheduling, a network timeout against a real server. Keep a small number of integration tests that use real time for those, and accept that they are slower, while the bulk of the time logic is unit-tested with the fake.
Do not fake time globally in a suite where some tests need real time, because the fake leaks. Install the fake per test and uninstall it after, so only the tests that opt in use it. This keeps the deterministic tests fast and the real-time integration tests honest.
Test the debounce, timeout, and expiry
Test a debouncer fires once after the delay and not before. Test a timeout fires after the timeout and calling the code before it fires does not double-fire. Test an expiry drops the value at the exact expiry and not before. Test a retry schedules the next attempt after the backoff and not sooner. Each of these is a boundary test that would be slow and flaky with a real wait.
# the whole suite runs instantly because no test waits in real time
npx vitest run --reporter=dot
# assert no test uses a real sleep for time-dependent behavior
Common pitfalls
Sleeping in a test for a timing behavior so it is slow and flaky, patching the global Date and leaking the fake into other tests, not testing the exact boundary so an off-by-one hides, faking time in an integration test that needs real timers, and comparing wall-clock values instead of the injected clock are the recurring mistakes. An injected clock, explicit advance, boundary tests, per-test fakes, and reading time from the injected source address them.
Conclusion
A fake clock makes time-dependent tests fast and deterministic. Inject the clock instead of using globals, advance it by an exact amount, assert the transition, and test just-before, exactly-at, and just-after each deadline. Self-check by asserting the debounce fires once after the delay and the expiry drops at the exact instant, with the suite running instantly. Then time logic is tested precisely rather than waited on.
Sources: MDN: Date, Sinon.js: Fake timers, Python: unittest.mock and time patching.
FAQ
- Why not just wait in the test?
- A real wait makes the test slow and flaky: it depends on the machine's load, and a slow CI can miss the window. A fake clock advances time instantly and deterministically, so the test asserts the exact behavior without waiting and without flakiness.
- How do I make code use an injectable clock?
- Pass the clock into the code as a dependency, or have the module read the clock from a single source that a test can replace. Then the code calls clock.now() and clock.setTimeout instead of the globals, and the test supplies a fake.
Report a problem with this articleOpens a pre-filled issue on GitHub.