#How to test a subject that is resided in a constructor (Jasmine)

4 messages · Page 1 of 1 (latest)

distant hound
#

I have a service "WebsocketService", which is injected into the "AccessControlService". Within this constructor I setup a subscription of the websocketService subject. My question is, how do I cover the branches within the subscription? I can't really use spyOn() because the websocketService is not accessible from the accessControlService.
Example setup is given here: https://stackblitz.com/edit/angular-ivy-ts-strict-enabled-sypuy6?file=src%2Fapp%2Faccess-control.service.ts

A angular-cli project based on @angular/animations, @angular/compiler, @angular/core, @angular/common, @angular/forms, @angular/platform-browser, @angular/platform-browser-dynamic, rxjs, tslib, @angular/router and zone.js.

meager cedar
#

Yes, you can use spyOn. You just need to get it from the TestBed, and spy on it before you construct the AccessControlService:

beforeEach(() => {
  TestBed.configureTestingModule({});
  const wsService = TestBed.inject(WebsocketService);
  spyOn(wsService, ...)...;
  service = TestBed.inject(AccessControlService);
});

Or you can simply create a mock with jasmine and provide it in your testing module:

beforeEach(() => {
  const wsService = jasmine.createSpyObj(...); // don't remember the exact syntax here
  TestBed.configureTestingModule({
    providers: [{ provide: WebWebsocketService, useValue: wsService }
  });
  service = TestBed.inject(AccessControlService);
});
distant hound
meager cedar
#

You can't call spyOn(wsService,"subscribe") since the service doesn't have any subscribe method. And I wouldn't subscribe in the service. You should subscribe from outside of the service, where you can actually use the messages you'll receive to do something more useful than logging them.