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



我正在尝试测试这两个异步函数。问题是每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();
});
}

测试:

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();
}));

简而言之,你不需要flush,你需要tick((,你应该按照你的期望在测试的底部添加以下内容:

discardPeriodicTasks(); 

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

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

test("test", fakeAsync(() => {
const getSpy = ...
component.ngOnInit();
tick(10000);
expect(getSpy).toHaveBeenCalled() . . .
discardPeriodicTasks(); 
}));

希望这能有所帮助,

如果this.postSubscription是公共变量,则可以在单元测试中取消订阅。

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();
// unsubscribe
component.postSubscription.unsubscribe();
}));

如果它是私有的,您可以在ngOnDestroy中取消订阅,并在单元测试中调用它。

ngOnDestroy() {
this.postSubscription.unsubscribe();
}
...
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();
// call ngOnDestroy to unsubscribe
component.ngOnDestroy();
}));

最新更新