Fake Clock For Deterministic Timer Tests
A controllable clock that makes timer dependent logic testable without real waiting, and drives pending callbacks in exact order.
Code
export class FakeClock {
constructor(start = 0) {
if (!Number.isFinite(start)) throw new TypeError("start must be a finite number");
this.now = start;
this.timers = [];
this.seq = 0;
}
setTimeout(fn, delay) {
if (!Number.isFinite(delay) || delay <= 0) {
throw new RangeError("delay must be a positive number");
}
const entry = { id: ++this.seq, due: this.now + delay, fn };
this.timers.push(entry);
this.timers.sort((a, b) => a.due - b.due || a.id - b.id);
return entry.id;
}
clearTimeout(id) {
this.timers = this.timers.filter((t) => t.id !== id);
}
advance(ms) {
if (!Number.isFinite(ms) || ms < 0) throw new RangeError("ms must be >= 0");
const target = this.now + ms;
for (;;) {
const next = this.timers[0];
if (!next || next.due > target) break;
this.timers.shift();
this.now = next.due;
next.fn();
}
this.now = target;
}
get pending() {
return this.timers.length;
}
}Tests that await real timers are slow and flaky, because machine load changes how many callbacks fire inside a fixed sleep.
Use case: engineers testing debounce, retry backoff or cache expiry
Inputs / outputs
- Input: a starting timestamp plus advance(ms) and runAll() controls
- Output: a clock object whose callbacks fire in scheduled order as virtual time advances
Error conditions
- advancing by a negative amount
- scheduling a callback with a non-positive delay
- a callback throwing
Approach
keep a sorted list of scheduled callbacks; advance moves virtual time forward and runs every due callback in order, including ones scheduled during the run.
Implementation
export class FakeClock {
constructor(start = 0) {
if (!Number.isFinite(start)) throw new TypeError("start must be a finite number");
this.now = start;
this.timers = [];
this.seq = 0;
}
setTimeout(fn, delay) {
if (!Number.isFinite(delay) || delay <= 0) {
throw new RangeError("delay must be a positive number");
}
const entry = { id: ++this.seq, due: this.now + delay, fn };
this.timers.push(entry);
this.timers.sort((a, b) => a.due - b.due || a.id - b.id);
return entry.id;
}
clearTimeout(id) {
this.timers = this.timers.filter((t) => t.id !== id);
}
advance(ms) {
if (!Number.isFinite(ms) || ms < 0) throw new RangeError("ms must be >= 0");
const target = this.now + ms;
for (;;) {
const next = this.timers[0];
if (!next || next.due > target) break;
this.timers.shift();
this.now = next.due;
next.fn();
}
this.now = target;
}
get pending() {
return this.timers.length;
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { FakeClock } from "./example.mjs";
test("runs callbacks in scheduled order", () => {
const clock = new FakeClock(0);
const seen = [];
clock.setTimeout(() => seen.push("b"), 20);
clock.setTimeout(() => seen.push("a"), 10);
clock.advance(5);
assert.deepEqual(seen, []);
clock.advance(5);
assert.deepEqual(seen, ["a"]);
clock.advance(10);
assert.deepEqual(seen, ["a", "b"]);
assert.equal(clock.pending, 0);
});
test("runs callbacks scheduled during advance", () => {
const clock = new FakeClock(0);
const seen = [];
clock.setTimeout(() => {
seen.push("outer");
clock.setTimeout(() => seen.push("inner"), 5);
}, 10);
clock.advance(100);
assert.deepEqual(seen, ["outer", "inner"]);
});
test("clearTimeout cancels a scheduled callback", () => {
const clock = new FakeClock();
let ran = false;
const id = clock.setTimeout(() => { ran = true; }, 10);
clock.clearTimeout(id);
clock.advance(50);
assert.equal(ran, false);
});
test("rejects invalid input", () => {
const clock = new FakeClock();
assert.throws(() => clock.setTimeout(() => {}, 0), RangeError);
assert.throws(() => clock.advance(-1), RangeError);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
single clock instance; no Date patching (only the injected scheduler); no async timer interleaving beyond ordering.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.