2
votes

I am working on testing a component which has a subscription within the ngOnInit method. Works fine when running in "the wild" but testing fails as there is no subscription object available. I have tried creating a stub svc to build the observable object within my unit test, but can't get it to work.

Here's 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 my Test Setup

//SvcStub
const usrSvcStub = {
 user : {
  FirstName: "Test",
  LastName: "User",
  Username: "testuser"
 }
}

//Providers Config
 providers: [
    {provide: UserService, useValue: {usrSvcStub}}
   ]

When the test fires, I can see through debug that it is loading my "StubSvc" but user is undefined and I cannot subscribe to it. Can someone point me in right direction? Screenie below shows when it loads the component's ngOnInit function and subscribes to the service observable.

enter image description here

1
you are returning an object, you need to return observable on userShashank Vivek
did u try my answerShashank Vivek
Yes I did. I had to cast behavior subject to an observable using .asOservable() and all worked. Accepting your answer.billy_comic

1 Answers

1
votes

Can you try

const usrSvcStub = {
 user : new BehaviorSubject<any>({
  FirstName: "Test",
  LastName: "User",
  Username: "testuser"
 })
}