Open ascdi opened 2 years ago
I suppose, I had the same problem. I have a simple http service, that has method getHeroes. If request is successfull, it returns array with objects. If request failed, it returns empty array. The code of this method is:
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl).pipe(catchError(() => of([])));
}
The code of test case for situation, when request failed is:
it('should return empty array via "getHeroes" method if request has failed', () => {
const mockError = new HttpErrorResponse({
url: 'api/heroes',
status: 500,
statusText: 'server error',
});
when(mockHttp.get('api/heroes')).thenReturn(throwError(() => mockError));
const service = createService();
expect(service.getHeroes()).toBeObservable(
cold('(a|)', {
a: [],
})
);
});
As you can see I used throwError operator, also I added a | symbol of marble syntax to test has passed. I'm not sure, it's a best way to solve the problem, but it's ONLY option (I tried a lots of variants over 1,5-2 hours!).
i am trying to test a path that leads into an
rxjs
catchError
function.Example Code:
Now i am Mocking the
next
Part usingmock
&instance
and tried boththenThrow
andthenReturn(throwError(
in Order to throw an error that could be catched bycatchError
. But i never reach theconsole.log
statement.Example:
How can i reach that path, mocking my
next.handle
?