How to mock Angular 4.3 httpClient an error response in testing

The expectOne method in HttpTestingController class returns a TestRequest object. This TestRequest class has a flush method which can be used to deliver

both successful and unsuccessful responses.

We can resolve the request by returning a body along with some additional response headers (if any). Relevant info can be found here.

Now, coming back to the point how you can do this. You can customize the below code snippet as per your use case.

http = TestBed.get(HttpTestingController);
let response: any;
let errResponse: any;
const mockErrorResponse = { status: 400, statusText: 'Bad Request' };
const data="Invalid request parameters";
apiService.get(somePath).subscribe(res => response = res, err => errResponse = err);
http.expectOne('url/being/monitored').flush(data, mockErrorResponse);
expect(errResponse).toBe(data);

NOTE: At the time of writing this comment, statusText is required in mockErrorResponse. Related info can be found here.

P.S.: The error method of TestRequest class can be used to simulate network error in our test case, as it expects an instance of Error. The following code snippet shows that.

http.expectOne(someUrl).error(new ErrorEvent('network error'));

Leave a Comment