prefer-context-mock
July 2, 2026 Β· View on GitHub
π Prefer the test context t.mock over the global mock.
πΌπ« This rule is enabled in the β
recommended config. This rule is disabled in the βοΈ unopinionated config.
Mocks created through the test context (t.mock) are automatically restored when the test finishes. The global mock exported from node:test is not β its mocks persist across tests until you manually call mock.reset()/mock.restoreAll(). Forgetting that leaks a mock into later tests, causing order-dependent failures that are hard to track down.
This rule reports state-creating calls on the global mock (fn, method, getter, setter, property, module, timers) and points you to the t.mock equivalent. The cleanup methods (mock.reset(), mock.restoreAll()) are not reported.
Examples
import {test, mock} from 'node:test';
// β
test('reads config', () => {
mock.method(fs, 'readFileSync', () => '{}');
});
// β
test('reads config', t => {
t.mock.method(fs, 'readFileSync', () => '{}');
});