0

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}));
Arco Voltaico
  • 860
  • 13
  • 29
  • 1
    You don't need the `HttpClientTestingModule` - you're testing the *component*, not the *service*. You shouldn't be using `HttpErrorResponse` for the same reason, that's a detail of the transport layer the service should conceal. But note that `of` creates an observable in a success state, not a failing state - you want to `throwError`. – jonrsharpe Apr 17 '20 at 13:19
  • 1
    try with throwError instead of of operator – Sayooj V R Apr 17 '20 at 13:28
  • If I update to cs.getActiveChannels = jasmine.createSpy('getActiveChannels').and.throwError('so awful'); then the test end with : Error: so awful at at UserContext. (http://localhost:9876/_karma_webpack_/src/app/pages/channels/channels.component.spec.ts:73:71) at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1) at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zon. ...... – Arco Voltaico Apr 17 '20 at 13:32
  • Testing succesfully now with and.returnValue(throwError({status: 404})); instead – Arco Voltaico Apr 17 '20 at 13:38
  • https://stackoverflow.com/questions/39960146/testing-error-case-with-observables-in-services – Arco Voltaico Apr 17 '20 at 13:39

0 Answers0