简体   繁体   中英

Jasmine Testing Subscription To Service Level Observable From OnInit Angular

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.

在此处输入图片说明

Can you try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM