简体   繁体   English

如何在角度 8 中为 rxjs 间隔编写测试用例?

[英]How to write test case for rxjs interval in angular 8?

I have one method "intervalCall()" into app.component.ts and sending the request every 60 seconds using rxjs interval, so want to test case for it for spect file, below is the method.我在 app.component.ts 中有一个方法“intervalCall()”,并使用 rxjs 间隔每 60 秒发送一次请求,所以想为它的 spect 文件测试用例,下面是方法。

intervalCall() {
    interval(60 * 1000)
      .pipe(mergeMap(() => this.XYZService.XYZmethod()))
      .subscribe((data: StatusDependents) => {
        if (data.status === 'UP') {
          location.reload();
        }
      });
  }

this.XYZService.XYZmethod() is my service call which I am sending every 60 seconds. this.XYZService.XYZmethod() 是我每 60 秒发送一次的服务调用。

I have write down below test case, still getting error with 1 periodic timer(s) still in the queue.我在测试用例下面写下了,仍然在队列中出现 1 个周期性计时器的错误。

 describe('#intervalCall', () => {
    it('should call intervalCall method when status is UP', fakeAsync(() => {
      const statusData: StatusDependents = { status: 'UP' };
      const statusSpy = jest.spyOn(userService, 'statusDependents').mockReturnValue(of(statusData));
      component.intervalCall();
      fixture.detectChanges();
      tick(180500);
      expect(statusSpy).toHaveBeenCalled();
      flush();
    }));
  });

Use fakeAsync.使用 fakeAsync。 See how it's used here: https://v8.angular.io/guide/testing在这里查看它是如何使用的: https ://v8.angular.io/guide/testing

The main advantage I've found is that you aren't waiting real seconds while unit testing, you can use tick(180500) to jump ahead 3 minutes and ½ seconds instantly.我发现的主要优势是您在单元测试时无需等待真正的秒数,您可以使用tick(180500)立即向前跳 3 分 ½ 秒。

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

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