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