【问题标题】:Angular cannot read property subscribe of undefined errorAngular 无法读取未定义错误的属性订阅
【发布时间】:2021-03-04 12:20:14
【问题描述】:

我遇到了这个奇怪的无法读取未定义错误的订阅,奇怪的是,它在独立运行时不会出现,但在不使用集中测试的情况下运行时几乎所有时间都会出现

我不知道为什么会出现此错误。我尝试了各种网站上的一些方法,例如添加 afterEach 循环。

谁能指出我的代码为什么会出错

【问题讨论】:

  • 可以分享一下你的getAccessGroup服务功能吗?
  • @AmanGojariya 它被嘲笑了。问题是它在构造函数中被订阅。在测试的这个时间点上,你仍然在 beforeEach 中,所以还没有设置 spy 的返回值。
  • 你试过了吗:accessGroupSpy.getAccessGroup.and.returnValue(throwError(new Error("oops"))
  • @Luxusproblem 不,我没有,但同样的问题发生在测试“当参数有 id”时

标签: angular typescript unit-testing karma-jasmine


【解决方案1】:

在您到达测试用例之前调用您的间谍:

beforeEach(() => {
    fixture = TestBed.createComponent(ViewAccessGroupComponent);  // HERE, the constructor is called
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

您可以将订阅移至ngOnInit,然后在调用fixture.detectChanges() 时完成订阅,因此您可以将该调用移至设置间谍结果的下方:

  it("#getAccessGroup should show error message if API fails ", () => {

    accessGroupSpy.getAccessGroup.and.returnValue(throwError({error:{message:"error"}}))
    
    fixture.detectChanges(); // HERE instead of in beforeEach

【讨论】:

  • 在 ngOnInit 生命周期内移动订阅会以任何方式影响整个应用程序吗??
  • 不,因为这始终是组件上调用的第一件事。一般来说,订阅应该始终在 ngOnInit 中完成......这基本上就是它的用途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 2019-04-06
相关资源
最近更新 更多