Angular RXJS HTTPClient not catching errors HttpErrorResponses

Viewed 417

Angular 12, I am trying to get a set of unit tests running where they will catch errors coming in the http response, but when the tests run the error is passed in the response body rather than as an error.

Spec.ts file

it('Test post method failure', () => {
      const expected: HttpErrorResponse = new HttpErrorResponse({
        error: 'Bad Request',
        status: 400,
        statusText: 'Bad Request'
      });
      service.post({ urlIdentifier: 'test', endpoint: '123' }).subscribe({
        next: res => {
          // This is being run
          console.log(res)
        },
        error: error => {
          // This is not run.
          expect(error.status).toBeCloseTo(expected.status);
          expect(error.statusText).toEqual(expected.error);
        }}

      );

Method being tested

export class HttpService {
  constructor(public http: HttpClient) {};
  post<T>({ urlIdentifier, endpoint, body }: HttpMethodsArguments): Observable<T> {
    const url: string = this.getBaseUrl(urlIdentifier) + endpoint;
    return this.http.post<T>(url, body, {
      headers: this.getHttpHeaders()
    }).pipe(
        catchError(err => {
          return throwError(err);
        })
      );
  }

LOG from res object: HttpErrorResponse(headers:..., status:400, statusText: "Bad Request" ...) The expected outcome I want is coming through just in the res object in the test instead of as an error. It's probably something small that I am missing but I can't solve this.

1 Answers

Melvin's comment was correct. An Error was not being thrown so Catch Error was not activating. I Added a pipe to throw the error in the case of an HttpErrorResponse.

export class HttpService {
  constructor(public http: HttpClient) {};
  post<T>({ urlIdentifier, endpoint, body }: HttpMethodsArguments): Observable<T> {
    const url: string = this.getBaseUrl(urlIdentifier) + endpoint;
    return this.http.post<T>(url, body, {
      headers: this.getHttpHeaders()
    }).pipe(
      map(x => {
        if (x instanceof HttpErrorResponse) {
          throw x;
        }
        return x;
        })
      )
      .pipe(
        catchError(err => {
          return throwError(err);
        })
      );
  }
Related