During my unit test, I encountered the same error message while throwing observable exceptions after mocking my services.
To resolve this issue, I made sure to pass the exact function and format inside Observable.throw
.
The code snippet below demonstrates how the service is called and subscribes to retrieve data, with a catch
block to handle errors like 400
:
this.search(event).catch((e: Response) => {
if (e.status === 400) {
console.log(e.json().message);
} else if (e.url) {
console.log('HTTP Error: ' + e.status + ' ' + e.statusText,
'URL: ' + e.url, 'Info: ' + e.json().message));
}
}).finally(() => {
this.loading = false;
}).subscribe((bData) => {
this.data = bData;
});
Within the service code:
search() {
return this.someService.getData(request)
.do((r) => {
this.someService.defaultHeaders.delete('skipAlert');
return r;
})
.map((r) => {
return r.businessObjectDataElements.length && r.businessObjectDataElements || null;
});
}
Unit Testing
I mocked the SomeService and ensured it returned observable data with all required methods intact. Everything seemed fine.
someServiceApi = fixture.debugElement.injector.get(SomeService);
spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));
However, when attempting to test the catch/error condition by using Observable.throw({})
, an error occurred as it expected a Response
type return from the service.
Below is the service mocking return that caused the error:
someServiceApi.getData
.and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));
To address this, I replicated the exact expected function in the return object instead of passing a Response
type value:
someServiceApi.getData
.and.returnValue(Observable.throw({status: 400, json: () => { return {message: 'not found error'}}, body: []}));
// see `json: () => { return {message: 'not found error'}}` inside return value