Currently, I am facing challenges testing a component that contains a subscription within the ngOnInit method. While everything runs smoothly in the actual application environment, testing fails because the subscription object is not accessible. I have attempted to create a stub svc to generate the observable object within my unit test, but unfortunately, it has been unsuccessful.
Below is an excerpt of my Service and Component code (abrv):
Component
ngOnInit() {
this.userSvc.user.subscribe(user => {
this.currentUser = user; //-- this.userSvc.user (which is an observable on that class) is available in the wild, but not when testing
})
}
UserService
//-- User Subscribe items
userSubject: BehaviorSubject<any> = new BehaviorSubject(null);
user = this.userSubject.asObservable(); // this is the property I'm subscribing to which gets set after login.
Here is how I have set up my Test:
//SvcStub
const usrSvcStub = {
user : {
FirstName: "Test",
LastName: "User",
Username: "testuser"
}
}
//Providers Configuration
providers: [
{provide: UserService, useValue: {usrSvcStub}}
]
During the test execution, I observe that my "StubSvc" is loaded, however, the user object is undefined and I cannot subscribe to it. I would appreciate any guidance on how to resolve this issue. The screenshot below illustrates the point at which the component's ngOnInit function is called and attempts to subscribe to the service observable.