Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Fake timers in node:test

Move the clock by hand in node:test and prove a debounce waits until the full delay after the last call.

You want to test a search box that fires 300 ms after the last keystroke. Waiting for real timers makes the test slow and leaves room for timing noise. With node:test, you can move a fake clock to the boundary and check both sides.

Test the last call on the fake clock

Enable the fake setTimeout inside the test. Node also mocks its matching clear function, so the debounce can cancel each previous timeout. Keep the timer calls global in the example.

Save this as debounce.test.mjs.

import assert from 'node:assert/strict'
import test from 'node:test'

function debounce(fn, delay) {
  let handle
  return (value) => {
    clearTimeout(handle)
    handle = setTimeout(() => fn(value), delay)
  }
}

test('search waits until 300 ms after the last input', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] })
  const calls = []
  const search = debounce((query) => calls.push(query), 300)

  search('c')
  t.mock.timers.tick(100)
  search('ca')
  t.mock.timers.tick(100)
  search('cat')

  t.mock.timers.tick(299)
  assert.deepEqual(calls, [])

  t.mock.timers.tick(1)
  assert.deepEqual(calls, ['cat'])
})

Run node --test debounce.test.mjs and expect one passing test. The clock moves through 500 ms of timer time without the test sleeping for half a second.

diagram

The debounce deadline

The last call schedules the only surviving timeout at 500 ms, 300 ms after cat.

Check just before the deadline

The third input happens at 200 ms, so its timeout is due at 500 ms. The first assertion runs at 499 ms and checks that none of the three calls fired. The next tick reaches the deadline, and the second assertion checks that the callback received only the last query.

Keep both assertions. If you delete the clearTimeout line, older callbacks can run before the last deadline. Checking the full array catches extra calls, including duplicates.

Use the mock on the test context so Node resets it at the end of the test. This example uses the options-object form of enable(), available since Node 20.11. The Node 22 test runner docs cover the paired clear function and why Node 22 prints an experimental warning.

If you adapt an existing module, check how it imports timers. A destructured timer import can bypass the mock. Start with a global setTimeout and one boundary assertion, then move the same check to the module under test.