如何使用 rxjs 计时器测试轮询?
How to test polling with rxjs timer?
我有一个 angular 组件,我在其中使用 rjxs 计时器在 ngOnInit 中进行了轮询,如下所示:
ngOnInit() {
timer(0, 60000). subscribe(() => {
this.getSomeStuff();
}
}
开个玩笑,我有一个函数的间谍:
const getSomeStuff = jest.spyOn( component, 'getSomeStuff' );
我的目标是测试“getSomeStuff”函数被调用了多少次。
例如:
0 毫秒后:
期待(getSomeStuffSpy).toHaveBeenCalledTimes(1);
应该是真的。
60000 毫秒(一分钟)后:
期待(getSomeStuffSpy).toHaveBeenCalledTimes(2);
应该是真的。
但是没有人工作,期望只通过 0,我不明白为什么。
我尝试使用 fakeAsync anch tick(),尝试使用 VirtualScheduler 以及我在其他问题上发现的所有内容,但似乎对我的情况没有任何帮助。
有人可以尝试不同的方法吗?
问题是,您可能会在 ngOnInit
开始计时。
如果你在beforeEach
钩子中调用fixture.detectChanges()
,定时器已经运行,你才能窥探应该调用的函数。
因此,要么将计时器移动到一个函数中,然后在 ngOnInit
中调用,要么必须修改测试以在每个测试中调用 fixture.detectChanges()
(见下文)。
此外,您必须在每次测试结束时调用 ngOnDestroy
或取消订阅计时器,否则您将收到类似 1 periodic timer(s) still in the queue.
.
的错误
因此您的测试可能如下所示:
beforeEach(async () => {
// other setup...
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// don't call fixture.detectChanges() here.
});
it('test 1', fakeAsync(() => {
const spy = spyOn(component, 'doStuff');
fixture.detectChanges();
tick(0);
expect(spy).toHaveBeenCalledTimes(1);
component.ngOnDestroy();
}));
我有一个 angular 组件,我在其中使用 rjxs 计时器在 ngOnInit 中进行了轮询,如下所示:
ngOnInit() {
timer(0, 60000). subscribe(() => {
this.getSomeStuff();
}
}
开个玩笑,我有一个函数的间谍:
const getSomeStuff = jest.spyOn( component, 'getSomeStuff' );
我的目标是测试“getSomeStuff”函数被调用了多少次。 例如:
0 毫秒后:
期待(getSomeStuffSpy).toHaveBeenCalledTimes(1);
应该是真的。
60000 毫秒(一分钟)后:
期待(getSomeStuffSpy).toHaveBeenCalledTimes(2);
应该是真的。
但是没有人工作,期望只通过 0,我不明白为什么。 我尝试使用 fakeAsync anch tick(),尝试使用 VirtualScheduler 以及我在其他问题上发现的所有内容,但似乎对我的情况没有任何帮助。
有人可以尝试不同的方法吗?
问题是,您可能会在 ngOnInit
开始计时。
如果你在beforeEach
钩子中调用fixture.detectChanges()
,定时器已经运行,你才能窥探应该调用的函数。
因此,要么将计时器移动到一个函数中,然后在 ngOnInit
中调用,要么必须修改测试以在每个测试中调用 fixture.detectChanges()
(见下文)。
此外,您必须在每次测试结束时调用 ngOnDestroy
或取消订阅计时器,否则您将收到类似 1 periodic timer(s) still in the queue.
.
因此您的测试可能如下所示:
beforeEach(async () => {
// other setup...
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// don't call fixture.detectChanges() here.
});
it('test 1', fakeAsync(() => {
const spy = spyOn(component, 'doStuff');
fixture.detectChanges();
tick(0);
expect(spy).toHaveBeenCalledTimes(1);
component.ngOnDestroy();
}));