茉莉花测试订阅可从OnInit角度观察到的服务水平

问题描述 投票:1回答:1

我正在测试ngOnInit方法中具有预订的组件。在“狂野”中运行时可以正常工作,但是由于没有可用的订阅对象,因此测试失败。我曾尝试创建一个存根svc来在我的单元测试中构建可观察对象,但无法使其正常工作。

这是我的服务和组件代码(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.

这是我的测试设置

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

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

当测试启动时,我可以通过调试看到它正在加载我的“ StubSvc”,但用户未定义,我无法订阅它。有人可以指出我正确的方向吗?下面的屏幕截图显示了何时加载组件的ngOnInit函数并订阅了可观察的服务。

enter image description here

javascript angular typescript jasmine karma-jasmine
1个回答
0
投票

您可以尝试

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

© www.soinside.com 2019 - 2024. All rights reserved.