I have a service that makes a HTTP get request as follows
public get(uri: string, params?: HttpParams): Observable<Object> {
return params ? this._http.get(uri, { params: params }) : this._http.get(uri)
.catch((error: HttpErrorResponse) => this.catchHttpError(error));
}
private catchHttpError(error: HttpErrorResponse) : Observable<Object> {
this._logger.error(`error occurred: ${error.message}`);
throw(error);
}
I have a test spec that can test the successful path. How do I:
Get the HttpTestingController to error so that the catchHttpError function is called?
Test that _httpService.get throws an error back up from the catchHttpError function?
My test so far looks like:
it('should make a get request and catch error', async(inject([HttpService, HttpTestingController], (_httpService: HttpService, backend: HttpTestingController) => {
spyOn(_httpService, 'get').and.callThrough();
let actualObjects: Object[] = [];
_httpService.get('/api/dummy/get/uri').subscribe((objects: Object[]) => {
actualObjects = objects;
});
backend.expectOne('/api/dummy/get/uri').flush(expectedObjects);
expect(_httpService.get).toHaveBeenCalledTimes(1);
expect(_httpService.get).toHaveBeenCalledWith('/api/dummy/get/uri');
expect(actualObjects).toEqual(expectedObjects);
expect(actualObjects.length).toBe(1);
//expect(_httpService.get).toThrow();
})));
Ended up going with this.
it('should make a get request and catch error', async(inject([HttpService, HttpTestingController], (_httpService: HttpService, backend: HttpTestingController) => {
spyOn(_httpService, 'get').and.callThrough();
let actualObjects: Object[] = [];
_httpService.get('/api/dummy/get/uri').subscribe(null, (response: HttpErrorResponse) => {
expect(response.message).toBe('Http failure response for /api/dummy/get/uri: 500 Server Error');
});
backend.expectOne('/api/dummy/get/uri').flush(expectedObjects, { status: 500, statusText: 'Server Error' });
expect(_httpService.get).toHaveBeenCalledTimes(1);
expect(_httpService.get).toHaveBeenCalledWith('/api/dummy/get/uri');
expect(actualObjects).toBeNull();
})));