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
#How to test a subject that is resided in a constructor (Jasmine)
4 messages · Page 1 of 1 (latest)
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);
});
I mean, sounds kinda good but wouldn't spyOn(wsService,"subscribe") override the subscription? I want to test the code within the subscription, not override it. And even if I didn't override it, how would i be able to invoke the subscription? .next would probably not work, since it is a WebSocketSubject and doesn't have a connection, right?
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.