6

I have a simple function that does this

ngOnInit() {
  if (this.session.getToken()) {
    this.isUserLogged = true;
  }

  this.loadingObserver = this.session.loadingObservable.subscribe(loading => this.isLoading = loading);
}

and my test is as follows

it('Testing ngOnInit() ...', async(() => {
  let spy = spyOn(services.session, 'getToken').and.returnValue('token');
  services.session.loadingObservable.subscribe(any => expect(component.isLoading).toEqual(false));
  component.ngOnInit();
  expect(component.isUserLogged).toEqual(true);
  expect(spy).toHaveBeenCalled();
}));

But in the code coverage of my application, the subscribe isn't covered. In fact, expecting false also works.

Do you have any idea on how to test a subscription ?

  • Possible duplicate of [Angular 2 RC5 Testing Promises in ngOnInit Not Working](https://stackoverflow.com/questions/39436230/angular-2-rc5-testing-promises-in-ngoninit-not-working) – Supamiu Jun 20 '17 at 13:04
  • I'll check if I find a solution for you, but I feel like testing if the subscription is defined should be enough, or you might trigger the loadingObservable to switch isLoading to either true or false. – Supamiu Jun 20 '17 at 13:13
  • Testing only the subscription won't test if isLoading has the correct value, abd this is where I'm stuck. I thought that only subscribing to it would allow an assertion, but it appears that it doesn't ... –  Jun 20 '17 at 13:14

1 Answers1

-1

Whether your handler code gets called or not on subscribe depends on the nature of the Observable you are subscribing to -- specifically its "hotness" or "coldness". Read this excellent explanation -- https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html -- and see where your "loadingObservable" falls in the taxonomy. But I suspect as was suggested in the comments, you need to force it to fire in your unit test.

  • Buddy, that's old ! I've got pretty far since that, but thank you for the reading ! –  Apr 18 '18 at 17:23