javascript / expert
Snippet
Deterministic Timer and Method Mocking with node:test
Node.js includes a native test runner with built-in mocking utilities. Using context-scoped t.mock, you can manipulate system timers deterministically and stub object methods without third-party mocking libraries.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { test } from 'node:test';import assert from 'node:assert';test('stubs timer and object method', (t) => {t.mock.timers.enable({ apis: ['setTimeout'] });const service = { fetchData: () => 'real data' };t.mock.method(service, 'fetchData', () => 'mocked data');let result = null;setTimeout(() => { result = service.fetchData(); }, 1000);t.mock.timers.tick(1000);assert.strictEqual(result, 'mocked data');});
nodejs
Breakdown
1
t.mock.timers.enable({ apis: ['setTimeout'] });
Enables mock timers specifically for setTimeout within the test context.
2
t.mock.method(service, 'fetchData', () => 'mocked data');
Overrides the target method on the service instance with a spy/stub implementation.
3
t.mock.timers.tick(1000);
Manually advances the virtual clock by 1000 milliseconds to trigger scheduled callbacks synchronously.