source: frontend/node_modules/eslint-plugin-jest/docs/rules/prefer-spy-on.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 1.3 KB
Line 
1# Suggest using `jest.spyOn()` (`prefer-spy-on`)
2
3When mocking a function by overwriting a property you have to manually restore
4the original implementation when cleaning up. When using `jest.spyOn()` Jest
5keeps track of changes, and they can be restored with `jest.restoreAllMocks()`,
6`mockFn.mockRestore()` or by setting `restoreMocks` to `true` in the Jest
7config.
8
9Note: The mock created by `jest.spyOn()` still behaves the same as the original
10function. The original function can be overwritten with
11`mockFn.mockImplementation()` or by some of the
12[other mock functions](https://jestjs.io/docs/en/mock-function-api).
13
14```js
15Date.now = jest.fn(); // Original behaviour lost, returns undefined
16
17jest.spyOn(Date, 'now'); // Turned into a mock function but behaviour hasn't changed
18jest.spyOn(Date, 'now').mockImplementation(() => 10); // Will always return 10
19jest.spyOn(Date, 'now').mockReturnValue(10); // Will always return 10
20```
21
22## Rule details
23
24This rule triggers a warning if an object's property is overwritten with a jest
25mock.
26
27### Default configuration
28
29The following patterns are considered warnings:
30
31```js
32Date.now = jest.fn();
33Date.now = jest.fn(() => 10);
34```
35
36These patterns would not be considered warnings:
37
38```js
39jest.spyOn(Date, 'now');
40jest.spyOn(Date, 'now').mockImplementation(() => 10);
41```
Note: See TracBrowser for help on using the repository browser.