Skip to content

jest/prefer-spy-on Style

🛠️ An auto-fix is available for this rule.

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.

Example

javascript
// invalid
Date.now = jest.fn();
Date.now = jest.fn(() => 10);

// valid
jest.spyOn(Date, "now");
jest.spyOn(Date, "now").mockImplementation(() => 10);

References

Released under the MIT License.