简体   繁体   中英

Mock HTTP Error response

I have a service that does the following:

  public fetchStuff(): Observable<MyModel> {
    const url = `httpURLHere`;

    return this.httpClient.get(url, { observe: 'response' }).pipe(
      map((res: any) => {
        console.warn(res);
        if ((res.status === 200 && res.body === null) || res.status === 404) {
          throw new Error("Error getting stuff");
        } else if (res.status === 500) {
          throw new Error("Error with API");
        } else {
          return <MyModel>res.body;
        }
      }),
      catchError(this.handleError)
    );
  }

  private handleError(error: Response | any) {
    console.error(error.message || error);

    return new ErrorObservable(error.message || error);
  }

I want to be able to test the logic inside the fetchStuff() function; this is proving to be more difficult than I first thought, though--since using:

httpMock.expectOne(url).error(new ErrorEvent('ERROR'), { status: 404 });

skips the inside logic and jumps straight to the handleError() function; and:

httpMock.expectOne(url).flush(null, { status: errorStatus, statusText: 'ERROR' });

will put the {status, statusText} in the body of the response.

I can't find anything anywhere else on how to mock an error response without jumping straight to the handleError() function.

You are doing it wrong. As the HttpClient documentation states anything other than 2XX-3XX response code are handle as error:

Two types of errors can occur. The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500. These are error responses.

Or something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator. These errors produce JavaScript ErrorEvent objects.

The HttpClient captures both kinds of errors in its HttpErrorResponse and you can inspect that response to figure out what really happened.

So basically your condition in map is dead code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM