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');
});