How to properly make mock throw an error in Jest? How to properly make mock throw an error in Jest? javascript javascript

How to properly make mock throw an error in Jest?


Change .mockReturnValue with .mockImplementation:

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

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


For Angular + Jest:

import { throwError } from 'rxjs';yourMockInstance.mockImplementation(() => {  return throwError(new Error('my error message'));});


For promises, can use https://jestjs.io/docs/mock-function-api#mockfnmockrejectedvaluevalue

test('async test', async () => {  const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));  await asyncMock(); // throws "Async error"});

For handling thrown errors, can use https://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest on how to handle it

const func = () => {  throw new Error('my error')}it('should throw an error', () => {    expect(func).toThrow()})