prefer-mock-method

July 2, 2026 Β· View on GitHub

πŸ“ Prefer mock.method() over assigning mock.fn() to an object property.

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

πŸ’‘ This rule is manually fixable by editor suggestions.

Replacing an object's method by assigning a mock.fn() to it (object.method = mock.fn()) discards the original implementation and leaves no way for the runner to restore it. mock.method(object, 'method') records the original, tracks calls, and restores it automatically (when using the test context's t.mock) or via mock.restoreAll().

This rule reports assignments of mock.fn() / t.mock.fn() to a member expression and suggests the equivalent mock.method() call. Any implementation passed to mock.fn() becomes the implementation argument of mock.method(). See also prefer-context-mock, which prefers the auto-restoring t.mock over the global mock.

Examples

import test from 'node:test';

test('mock', t => {
	// ❌
	object.method = t.mock.fn(() => 'stub');

	// βœ…
	t.mock.method(object, 'method', () => 'stub');
});