Skip to content

Commit 37267a5

Browse files
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#mockfngetmockimplementation
1 parent fe7f28c commit 37267a5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/MockFunctionAPI.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,32 @@ import TOCInline from '@theme/TOCInline';
1919

2020
## Reference
2121

22+
### `mockFn.getMockImplementation()`
23+
24+
Returns the current implementation of the mock function set by [`mockImplementation()`](#mockfnmockimplementationfn). Returns `undefined` if no implementation has been set.
25+
26+
```js tab
27+
const mockFn = jest.fn();
28+
29+
mockFn.getMockImplementation(); // undefined
30+
31+
mockFn.mockImplementation(() => 42);
32+
33+
mockFn.getMockImplementation(); // () => 42
34+
```
35+
36+
```ts tab
37+
import {jest} from '@jest/globals';
38+
39+
const mockFn = jest.fn<() => number>();
40+
41+
mockFn.getMockImplementation(); // undefined
42+
43+
mockFn.mockImplementation(() => 42);
44+
45+
mockFn.getMockImplementation(); // () => 42
46+
```
47+
2248
### `mockFn.getMockName()`
2349

2450
Returns the mock name string set by calling [`.mockName()`](#mockfnmocknamename).

0 commit comments

Comments
 (0)