0

below are 2 methods in my service file

    public getStates(countryId: number) {
          let url = this.configManagerService.statesApiUrl;
          const httpHeaders = this.getHeaders();
          return this.httpClient.get(`${url}/${countryId}`, { headers: httpHeaders }).pipe(
            catchError(this.handleError)
          );
    }

    public handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError('Value list currently not available.');
    }  

I am not able to write a unit test case which covers the handleError method. Can somebody please educate me on this? Thanks.

vamsi
  • 1,488
  • 3
  • 28
  • 66

1 Answers1

0

You need to use HttpClientTestingModule and flush an error for the API call.

This is a good source but it seems like he is not testing the error route.

Look at this to see how to mock an error for the Http Call. Once you mock an error, the handleError method should be called.

AliF50
  • 16,947
  • 1
  • 21
  • 37