I am just testing that a component will show an error alert when a call to a service is returning a 404 error.
The component method:
getChannels() {
this.channelService.getActiveChannels()
.subscribe(
(result) => {
// whatever.
},
(error) => {
this.alertService.showError('Error', 'No Connection');
console.log(error);
}
);
The service method
getActiveChannels() {
return this.http.get<any>(api.apiDomain + 'channels')
.pipe(map((response) => response));
Ands the test spec :
it('error alert called when get channels thrown an error', () => {
const as = fixture.debugElement.injector.get(AlertService);
const error = new HttpErrorResponse({error: 'foo', status: 0});
const cs = fixture.debugElement.injector.get(ChannelService);
jasmine.getEnv().allowRespy(true);
cs.getActiveChannels = jasmine.createSpy('getActiveChannels').and.returnValue(of(error));
component.getChannels();
expect(as.showError).toHaveBeenCalledWith('Error', 'No Connection');
});
This approach, overriding the existing spy, works as a charm, when returning any array value. But when I return this error, if I debug I see that the subscriber handles that error as a proper result, not as an error, so it never triggers the alert.
I'd like to keep my test as simple as possible without using HttpClientTestingModule that I think is overkilling for that simple task.
SOLUTION:
cs.getActiveChannels = jasmine.createSpy('getActiveChannels').and.returnValue(throwError({status: 404}));