Jest – testing httpClient rejected promise

Issue

I have an Nest.js application and I’m trying to test a method that has a simple httpClient request, but I can’t find a way to test the catch block from my code.

  async getUser(): Promise<any> {
    try {
      return lastValueFrom(
        this.httpService.get('https://external.url')
        }).pipe(map(response => response.data))
      )
    } catch (error) {
      throw Error(error)
    }
  }

Here is the block that my promise gets fulfilled and tested

  it('testing success', async () => {
    const result: AxiosResponse = {
      data: {},
      headers: {},
      config: {},
      status: 200,
      statusText: 'OK',
    }

    jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result))
    const response = mockSuccessRespose
    expect(await service.getUser()).toEqual(response)
  })

Now I’m trying to test it with a rejection condition

  it('testing exception', async () => {
   jest.spyOn(httpService, 'get').mockReturnValue(throwError(() => Error('error')))
    await expect(service.getUser()).rejects.toThrow('error')
  })

If I run this last test it passes, but If I run jest coverage the ‘throw Error(error)’ line is never called.

Solution

You’re not awaiting the result of the promise in the try-catch block, so the exception is uncaught. The correct version would be:

async getUser(): Promise<any> {
  try {
    return await lastValueFrom(
      this.httpService.get('https://external.url').pipe(map(response => response.data))
    );
  } catch (error) {
    throw Error(error)
  }
}

Answered By – Joulukuusi

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.