Angular HttpTestingController testing response type blob error responses

22 Views Asked by At

Trying to test the simple case of API call with some additional mapping done on both success and error responses.

    return this.http.post(someEndpoint, formData, {
      responseType: 'blob',
      observe: 'response',
      headers: new HttpHeaders({
        'Accept': 'text/csv'
      })
    }).pipe(
      map(blobResponse => {
        // ...
      }),
      catchError( async (err: HttpErrorResponse)=> {
        const customErrorMessage = await err.error.text();
        throw customErrorMessage;
      })
    );

I'm able to test the success scenario logic using

    myApi.someMethod(mock).subscribe({
      next: (res) => {
        expect(res).toEqual(someResponse);
      }
    });


    const req = httpTestingController.expectOne(someEndpoint);
    expect(req.request.method).toEqual('POST');

    req.event(responseMock);

    httpTestingController.verify();

Unfortunately I can't test the error scenario the same way, as req.flush(...) with HttpErrorResponse as a param always results in the Error: Automatic conversion to Blob is not supported for response type. error.

I tried to use req.error(...) :

const req = httpTestingController.expectOne(someEndpoint);

...

req.error(new ProgressEvent('error'), {status: mockErrorStatus, statusText: mockErrorMessage});

...

httpTestingController.verify();

It seems to be working as code from catchError is reached but it fails as there is no blob in the mocked payload so await err.error.text() just fails.

Is there any known way to test such scenarios? Maybe the code itself is written in a way that it is untestable?

I'm using jasmine 3.6, karma 6.3 and an Angular 16.

0

There are 0 best solutions below