typestar

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

  1. t.mock.timers.enable takes the APIs to fake.
  2. tick advances the clock by that many milliseconds.
  3. Nothing sleeps, so the test stays fast.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Mocks & time, step 6 of 9 in Testing with node:test.

← Previous Next →