如何在angular 8中为rxjs interval编写测试用例?



我有一个方法"intervalCall()"导入到app.component.ts中,并使用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周期定时器(s)仍然在队列中。

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分半秒。

最新更新