How to properly make mock throw an error in Jest?

Change .mockReturnValue with .mockImplementation:

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

in case you want to assert

   test('the fetch fails with an error', () => {
     return expect(fetchData()).rejects.toMatch('error');
   });

If it’s a promise you can also to .rejects www.jestjs.io/docs/en/asynchronous#resolves–rejects

Leave a Comment