How to properly make mock throw an error in Jest?

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

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

How to properly make mock throw an error in Jest?

To properly make mock throw an error in Jest, we call the mockImplementation method and throw an error in the callback we call the method with.

For instance, we write

it("should throw error if email not found", async () => {
  callMethod
    .mockImplementation(() => {
      throw new Error("User not found [403]");
    })
    .mockName("callMethod");

  const query = FORGOT_PASSWORD_MUTATION;
  const params = { email: "[email protected]" };
  const result = await simulateQuery({ query, params });

  console.log(result);
  expect(callMethod()).rejects.toMatch("User not found [403]");
});

to call callMethod.mockImplementation with a callback that throws and error.

Then we use

expect(callMethod()).rejects.toMatch("error");

to check the callMethod throws an error with the given content.

Conclusion

To properly make mock throw an error in Jest, we call the mockImplementation method and throw an error in the callback we call the method with.