[英]How to write test case for rxjs interval in angular 8?
我在 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() 是我每 60 秒发送一次的服务调用。
我在测试用例下面写下了,仍然在队列中出现 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();
}));
});
使用 fakeAsync。 在这里查看它是如何使用的: https ://v8.angular.io/guide/testing
我发现的主要优势是您在单元测试时无需等待真正的秒数,您可以使用tick(180500)
立即向前跳 3 分 ½ 秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.