How to make a mock throw an error in Jest?

Sometimes, we want to make a mock throw an error in Jest.

In this article, we’ll look at how to make a mock throw an error in Jest.

How to make a mock throw an error in Jest?

To make a mock throw an error in Jest, we can call mockImplementation with a function that throws an error.

For instance, we write:

yourMockInstance.mockImplementation(() => {
  throw new Error();
});

to use throw to thrown an error in the mocked implementation of yourMockInstance.

If we’re mocking async functions, we can use mockRejectedValue to mock the value of a rejected promise returned by the async function.

For instance, we write

test('async test', async () => {
  const yourMockFn = jest.fn().mockRejectedValue(new Error('Async error'));

  await yourMockFn();
});

then we should see 'Async error' as the promise rejection message when we call yourMockFn.

Conclusion

To make a mock throw an error in Jest, we can call mockImplementation with a function that throws an error.