Senior LevelNode JS
How do you use native node:test mocking (t.mock) and coverage flags in Node 20+?
❓ Interview Prompt: Explain native `node:test` mocking (`t.mock.fn`, `t.mock.method`), timer mocking (`t.mock.timers`), and `--experimental-test-coverage`.
Node 20+ 'node:test' includes full function and timer mocking capabilities ('t.mock'):
Features:
•
't.mock.fn()': Creates mock functions.
•
't.mock.timers.enable()': Fast-forwards time for testing 'setTimeout' without real-time delays!
Code Implementation Example
javascript
import test from 'node:test';
import assert from 'node:assert/strict';
test('Mocking API functions with node:test', (t) => {
const mockFn = t.mock.fn((a, b) => a + b);
assert.strictEqual(mockFn(2, 3), 5);
assert.strictEqual(mockFn.mock.callCount(), 1);
});💡Mocking functions using native node:test t.mock.
🎯 Interview Key Takeaway
Use t.mock in native node:test for zero-dependency function and timer mocking.
#node:test#mocking#Testing#Senior
Back to all Node JS Questions→