javascript / expert
Snippet
Deterministic Time Travel Testing using node:test Mocking Utilities
Testing asynchronous delay structures like timers can introduce non-determinism and slow down test suites. Using native Node.js test runner context mocks (t.mock.timers), virtual clocks can be fast-forwarded synchronously without introducing real-time delays.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { test } from 'node:test';import assert from 'node:assert';test('advances timer deterministically', (t) => {t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });let executed = false;setTimeout(() => { executed = true; }, 5000);t.mock.timers.tick(5000);assert.strictEqual(executed, true);});
nodejs
Breakdown
1
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
Replaces native time APIs with mock timers scoped to the test context.
2
setTimeout(() => { executed = true; }, 5000);
Schedules a delayed callback without actual process waiting.
3
t.mock.timers.tick(5000);
Synchronously advances internal mock clock by 5000 milliseconds.
4
assert.strictEqual(executed, true);
Verifies immediate synchronous resolution of the timed callback.