javascript / expert
Snippet
Automated Function and Timer Mocking with node:test Mock API
Node.js provides built-in mocking utilities via the node:test context (t.mock). It allows tracking function invocations, inspecting call arguments, and faking system timers without third-party libraries.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { test } from 'node:test';import assert from 'node:assert/strict';test('verifies mock timer and function invocation tracking', (t) => {const fn = t.mock.fn((a, b) => a + b);assert.equal(fn(2, 3), 5);assert.equal(fn.mock.callCount(), 1);assert.deepEqual(fn.mock.calls[0].arguments, [2, 3]);t.mock.timers.enable({ apis: ['setTimeout'] });let executed = false;setTimeout(() => { executed = true; }, 1000);t.mock.timers.tick(1000);assert.equal(executed, true);});
nodejs
Breakdown
1
const fn = t.mock.fn((a, b) => a + b);
Creates a tracked spy wrapping the target implementation inside the test context.
2
t.mock.timers.enable({ apis: ['setTimeout'] });
Fakes native time APIs to enable synchronous, deterministic execution of timer callbacks.
3
t.mock.timers.tick(1000);
Advances the virtual clock forward by 1000 milliseconds to trigger registered timeouts.