【问题标题】:How to test polling with rxjs timer?如何使用 rxjs 计时器测试轮询?
【发布时间】:2021-11-18 11:06:42
【问题描述】:

我有一个角度组件,我在其中使用 rjxs 计时器在 ngOnInit 中进行了轮询,如下所示:

ngOnInit() {
  timer(0, 60000). subscribe(() => {
    this.getSomeStuff();
  }
}

开玩笑的是,我有一个函数的间谍:

const getSomeStuff = jest.spyOn( component, 'getSomeStuff' );

我的目标是测试“getSomeStuff”函数被调用了多少次。 例如:

  • 0 毫秒后:

    expect(getSomeStuffSpy).toHaveBeenCalledTimes(1);

应该是真的。

  • 60000 毫秒(一分钟)后:

    expect(getSomeStuffSpy).toHaveBeenCalledTimes(2);

应该是真的。

但是没有人工作,期望通过只有0,我不明白为什么。 我尝试了 fakeAsync anch tick(),我尝试了 VirtualScheduler 以及我在其他问题上找到的所有内容,但我的案例似乎没有任何效果。

谁有不同的方法可以尝试?

【问题讨论】:

    标签: angular timer rxjs jestjs observable


    【解决方案1】:

    问题是,您可能在ngOnInit 中启动计时器。

    如果您在 beforeEach 钩子中调用 fixture.detectChanges(),则计时器已经在运行,然后您才能窥探应调用的函数。

    因此,要么将计时器移到一个函数中,然后在 ngOnInit 中调用,要么必须修改测试以在每个测试中调用 fixture.detectChanges()(见下文)。

    此外,您必须在每次测试结束时调用ngOnDestroy 或取消订阅计时器,否则您将收到类似1 periodic timer(s) still in the queue. 的错误。

    所以您的测试可能如下所示:

    beforeEach(async () => {
      // other setup...
    
      fixture = TestBed.createComponent(AppComponent);
      component = fixture.componentInstance;
    
      // don't call fixture.detectChanges() here.
    });
    
    it('test 1', fakeAsync(() => {
      const spy = spyOn(component, 'doStuff');
    
      fixture.detectChanges();
    
      tick(0);
    
      expect(spy).toHaveBeenCalledTimes(1);
    
      component.ngOnDestroy();
    }));
    

    【讨论】:

    • 感谢您的回答。我发现了其他问题,但你帮我解决了这个问题。
    猜你喜欢
    • 2022-01-06
    • 2017-05-30
    • 2021-12-29
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2018-02-22
    相关资源
    最近更新 更多