I have the same error message when I ran my unit test and throwing an observed exception after mocking my services.
I resolved it by passing the exact function and format inside Observable.throw .
The actual code that calls the service and subscribe to receive data. note that catch handles error 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; });
Code inside the service
search() { return this.someService.getData(request) .do((r) => { this.someService.defaultHeaders.delete('skipAlert'); return r; }) .map((r) => { return r.businessObjectDataElements.length && r.businessObjectDataElements || null; }); }
Device testing
I made fun of SomeService and return the observed data and its fine, because it has all the necessary methods.
someServiceApi = fixture.debugElement.injector.get(SomeService); spyOn(someServiceApi, 'getData').and.returnValue(Observable.of({}));
The above code is okey, but when I tried to check the catch / error condition by passing Observable.throw({}) , it showed me an error since it was expecting a Response type to return from the service.
So below mocking service return gave me this error.
someServiceApi.getData .and.returnValue(Observable.throw(new Response({status: 400, body: [], message: 'not found error'})));
So, I fixed it by replicating the exact expected function in my return object, rather passing a value of type Response .
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
Aniruddha das
source share