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', () => '{}');
});