Commit 37267a5
committed
docs: Document getMockImplementation()
`getMockImplementation()` was made a public method in commit 89119e4 in 2016 and in public TypeScript types since commit 95b94e8 in 2020 but it was never documented.
Motivation
---
This method has become more necessary with Jest's support for ESM. Previously, you could
extend manual mocks using jest.spyOn():
```js title="__mocks__/module.js"
export function fn() { /* default mock implementation */ }
```
```js title="__tests__/module.test.js"
const originalFn = module.fn;
jest.spyOn(module, 'fn').mockImplementation((...args) => {
// Add custom logic for the test here
return originalFn(...args);
});
```
However, spyOn doesn't work with ESM because module object properties are read-only.
The workaround is to use getMockImplementation():
```js title="__mocks__/module.js"
export const fn = jest.fn(() => { /* default mock implementation */ });
```
```js title="__tests__/module.test.js"
const originalImpl = jest.mocked(module.fn).getMockImplementation();
jest.mocked(module.fn).mockImplementation((...args) => {
// Add custom logic for the test here
return originalImpl?.(...args);
});
```
Test Plan
---
1. Build and serve the docs locally: `cd website && yarn install && yarn fetchSupporters && yarn start`
2. Browse to http://localhost:3000/docs/next/mock-function-api#mockfngetmockimplementation1 parent fe7f28c commit 37267a5
1 file changed
+26
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
22 | 48 | | |
23 | 49 | | |
24 | 50 | | |
| |||
0 commit comments