jest/prefer-spy-on Style
What it does
When mocking a function by overwriting a property you have to manually restore the original implementation when cleaning up. When using jest.spyOn()
Jest keeps track of changes, and they can be restored with jest.restoreAllMocks()
, mockFn.mockRestore()
or by setting restoreMocks
to true
in the Jest config.
Note: The mock created by jest.spyOn()
still behaves the same as the original function. The original function can be overwritten with mockFn.mockImplementation()
or by some of the other mock functions.
Why is this bad?
Directly overwriting properties with mock functions can lead to cleanup issues and test isolation problems. When you manually assign a mock to a property, you're responsible for restoring the original implementation, which is easy to forget and can cause tests to interfere with each other. Using jest.spyOn()
provides automatic cleanup capabilities and makes your tests more reliable.
Examples
Examples of incorrect code for this rule:
Date.now = jest.fn();
Date.now = jest.fn(() => 10);
Examples of correct code for this rule:
jest.spyOn(Date, "now");
jest.spyOn(Date, "now").mockImplementation(() => 10);
How to use
To enable this rule in the CLI or using the config file, you can use:
oxlint --deny jest/prefer-spy-on --jest-plugin
{
"plugins": ["jest"],
"rules": {
"jest/prefer-spy-on": "error"
}
}