javascript / expert
Snippet
Advanced Dependency Mocking with node:test
Node.js 20+ includes a built-in mock object in the test runner context. It allows for method spying and stubbing directly on system modules or objects without requiring external libraries like Sinon or Jest, reducing test overhead and maintenance.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import test from 'node:test';import assert from 'node:assert';import fs from 'node:fs';test('mocking fs.readFile', async (t) => {t.mock.method(fs, 'readFile', (path, cb) => {cb(null, Buffer.from('mocked content'));});fs.readFile('real.txt', (err, data) => {assert.strictEqual(data.toString(), 'mocked content');});});
nodejs
Breakdown
1
test('mocking fs.readFile', async (t) => {
The test context 't' provides access to the mocking utility.
2
t.mock.method(fs, 'readFile', (path, cb) => {
Intercepts calls to the 'readFile' method on the global 'fs' object.
3
cb(null, Buffer.from('mocked content'));
Simulates a successful asynchronous file read with custom data.
4
assert.strictEqual(data.toString(), 'mocked content');
Verifies that the code under test interacted with our mock correctly.