Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@jest/mock): Add withImplementation #13281

Merged
merged 16 commits into from Sep 23, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/MockFunctionAPI.md
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
jeppester marked this conversation as resolved.
Show resolved Hide resolved
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.
jeppester marked this conversation as resolved.
Show resolved Hide resolved

```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