【问题标题】:Unit test a subscription in ngOnInit not working对 ngOnInit 中的订阅进行单元测试不起作用
【发布时间】:2019-03-07 11:16:52
【问题描述】:

我已经订阅了 ngOnInit 上的 observable,现在我正在尝试为此编写测试,但这似乎不起作用。

这是我要测试的课程

ngOnInit() {
  this.myService.updates$.pipe(takeUntil(unsusbribe$))
   .subscribe(update => {
     this.feeds = update;
  })
}

这是我的单元测试

it('should set feeds when an update is sent', fakeAsync(() => {
const update = 'fakeUpdate';
component.ngOnInit();
  const serviceSpy = spyOn(myService, 'updates$').and.returnValue(timer(500).pipe(mapTo(update)))
tick(500);
expect(serviceSpy).toHaveBeenCalled(); 
}))

此测试失败并出现错误Expected spy updates$ to have been called.

谁能帮我解决这里的问题。

【问题讨论】:

  • 您的测试中在哪里调用了 ngOnInit?如果不调用,为什么要调用你的间谍?
  • @JBNizet 我刚刚更新了问题......它在 ngOnInit() 上被调用。所以我调用了 component.ngOnInit()

标签: angular jasmine karma-jasmine angular-unit-test


【解决方案1】:

使用间谍服务的正确方法。请试试这个。

  it('should set feeds when an update is sent', fakeAsync(() => {
    const update = 'fakeUpdate';
    const serviceSpy = spyOn(myService, 'updates$');
    serviceSpy.and.returnValue(timer(500).pipe(mapTo(update)))
    tick(500);
    expect(serviceSpy).toHaveBeenCalled(); 
  }))

【讨论】:

  • 感谢您的帮助,但这似乎仍然不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
相关资源
最近更新 更多