角度测试异步函数生成错误 - 1 个周期性计时器仍在队列中

any*_*y07 1 testing junit unit-testing typescript angular

我正在尝试测试这两个异步函数。问题是其中一个函数每 10 秒自动调用一次。我尝试使用tick()或flush(),但仍然遇到相同的错误:1个周期性计时器仍在队列中。我该如何解决?我的代码:

 ngOnInit(): void {
    const dialogRef = this.openProgressDialog();
    this.getSubscription = this.getAll();
    dialogRef.close();

    this.postSubscription = interval(10000).subscribe(() => {
      this.sendAll();
      this.dataSource.data = this.jobs;
      this.table.renderRows();
    });
  }
Run Code Online (Sandbox Code Playgroud)

考试:

test("test", fakeAsync(() => {
    const getSpy = spyOn(otdRepositoryMock, "getAll").and.returnValue(of(jobs));
    const getSubscribeSpy = spyOn(otdRepositoryMock.getAll(), "subscribe");
    const postSpy = spyOn(otdRepositoryMock, "sendAll").and.returnValue(of(jobs));
    const postSubscribeSpy = spyOn(otdRepositoryMock.sendAll([2]), "subscribe");
    component.ngOnInit();
    //tick();
    //flush();
    expect(getSpy).toHaveBeenCalled();
    expect(getSubscribeSpy).toHaveBeenCalled();
    expect(postSpy).toHaveBeenCalled();
    expect(postSubscribeSpy).toHaveBeenCalled();
  }));
Run Code Online (Sandbox Code Playgroud)

djm*_*tte 5

简而言之,您不需要flush,您确实需要tick(),并且您应该按照您的期望将以下内容添加到测试的底部:

      discardPeriodicTasks(); 
Run Code Online (Sandbox Code Playgroud)

这将在执行下一个测试之前清除您拥有的所有剩余计时器。

因此,在您的示例中(为简洁起见进行了编辑):

test("test", fakeAsync(() => {

   const getSpy = ...

   component.ngOnInit();
   tick(10000);

   expect(getSpy).toHaveBeenCalled() . . .

   discardPeriodicTasks(); 
 }));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,