简体   繁体   English

从 OnInit Angular 可观察到的服务级别的 Jasmine 测试订阅

[英]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.我正在测试一个在 ngOnInit 方法中有订阅的组件。 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.我已经尝试创建一个存根 svc 来在我的单元测试中构建可观察对象,但无法让它工作。

Here's my Service and Component code (abrv):这是我的服务和组件代码 (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.当测试触发时,我可以通过调试看到它正在加载我的“StubSvc”,但用户未定义,我无法订阅它。 Can someone point me in right direction?有人可以指出我正确的方向吗? Screenie below shows when it loads the component's ngOnInit function and subscribes to the service observable.下面的 Screenie 显示了它何时加载组件的 ngOnInit 函数并订阅服务 observable。

在此处输入图片说明

Can you try你能试一下吗

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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