Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/MockFunctionAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,43 @@ test('async test', async () => {
});
```

### `mockFn.withImplementation(fn, callback)`

Accepts a function which should be temporarily used as the implementation of the mock while the callback is being executed.

```js tab
test('test', () => {
const mock = jest.fn(() => 'outside callback');

mock.withImplementation(
() => 'inside callback',
() => {
mock(); // 'inside callback'
},
);

mock(); // 'outside callback'
});
```

`mockFn.withImplementation` can be used regardless of whether or not the callback is asynchronous (returns a promise like object). If the callback is asynchronous a promise will be returned. Awaiting the promise will await the callback and reset the implementation.

```js
test('async test', async () => {
const mock = jest.fn(() => 'outside callback');

// We await this call since the callback is async
await mock.withImplementation(
() => 'inside callback',
async () => {
mock(); // 'inside callback'
},
);

mock(); // 'outside callback'
});
```

## TypeScript Usage

:::tip
Expand Down