我有一个角度组件来轮询新数据,并且在我们等待响应时,它每X秒更新一次UI中的消息。它循环显示一个简单的消息字符串数组。
一旦收到正确的数据,我们将导航到相应的页面。
this.pollSubscription = timer(0, pollTimeInSeconds)
.pipe(
//convert each observable iteration into an interval in seconds
map((count: number) => count * pollTimeInSeconds),
//keep going if we are below the max poll time
takeWhile((time: number) => time < this.maxPollTime),
//update the UI message
tap((time: number) => this.updateCurrentMessage(time)),
//
switchMap(() => this.getDataOrError$())
)
.subscribe(
//navigate to the correct page
(d: IData) => this.navigateBasedOnStatus(d),
//If an error occurs, OR the observable completes (which should not happen), navigate to the error page
() => this.navigateToError(),
() => this.navigateToError()
);
我想测试这种行为,但是我不完全确定如何针对这种情况模拟timer
。我看到了this SO answer,但我无法根据自己的情况进行工作。
理想情况下,我想构建一个类似这样的测试,以确保显示每条消息,并且如果计时器的时间比预期的长,它将循环回到第一条消息:
it('should show every status as the timer changes', fakeAsync(() => {
tick(0);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message one');
tick(1000);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message two');
tick(2000);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message three');
//etc...
}));
编辑我正在基于以下一些评论进行新的测试,但这仍然无法正常工作
let timerTick: (milliseconds: number) => void;
beforeEach(() => {
let fakeNow = 0;
timerTick = (milliseconds: number): void => {
fakeNow += milliseconds;
tick(milliseconds);
};
asyncScheduler.now = (): number => fakeNow;
});
afterEach(() => {
delete asyncScheduler.now;
});
it('should show every status as the timer changes', fakeAsync(() => {
fixture.detectChanges(); // triggers ngOnInit()
const pollTimeInSeconds = loginPollTime * 1000;
let received: number | undefined;
timer(0, pollTimeInSeconds, asyncScheduler).subscribe((value: number) => received = value);
console.log(received);
timerTick(0);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message one');
console.log(received)
timerTick(pollTimeInSeconds);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message two');
console.log(received)
timerTick(pollTimeInSeconds * 2);
fixture.detectChanges();
expect(debugEl.nativeElement.innerText.trim()).toEqual('Message three');
console.log(received)
}));
茉莉花的输出是:
Expected 'Message one' to equal 'Message two'.
Expected 'Message one' to equal 'Message three'.
控制台输出为:
> undefined
> 0
> 1
> 3