Faking time in JavaScript
Mock timers make a delay instant and deterministic.
import test from "node:test";
import assert from "node:assert/strict";
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
test("debounce fires once, after the wait", (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const calls = [];
const debounced = debounce((value) => calls.push(value), 100);
debounced("a");
debounced("b");
assert.deepEqual(calls, []);
t.mock.timers.tick(100);
assert.deepEqual(calls, ["b"]);
});
How it works
t.mock.timers.enabletakes the APIs to fake.tickadvances the clock by that many milliseconds.- Nothing sleeps, so the test stays fast.
Keywords and builtins used here
constfromfunctionimportletreturn
The run, in numbers
- Lines
- 23
- Characters to type
- 512
- Tokens
- 148
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 81 seconds.
Step 2 of 2 in Mocks & time, step 6 of 9 in Testing with node:test.