有这个 Angular 组件:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { asyncScheduler, Observable, of, queueScheduler, scheduled } from 'rxjs';
@Component({
selector: 'test-component',
templateUrl: './test-component.component.html'
})
export class TestComponentComponent implements OnInit {
value: string;
constructor() { }
ngOnInit(): void {
const data$ = this.fetchDataScheduler();
data$
.subscribe(value => {
this.value = value;
});
}
private fetchDataScheduler(): Observable<string> {
return scheduled(of('foo'), asyncScheduler);
}
}
并且测试失败:
it('async - test setTimeout', fakeAsync(() => {
expect(component.value).toBeFalsy();
fixture.detectChanges(); // ngOnInit
expect(component.value).toBeFalsy();
flush();
expect(component.value).toBe('foo'); // <- fails here
}));
flush()
应该刷新所有宏任务,但它没有。为什么?如果我使用
tick()
,则测试通过。(以上截图由 Jest 和 Wallaby 插件提供。)
为什么不通过
flush()
但正在通过 tick()
?flush :
Simulates the asynchronous passage of time for the timers in the fakeAsync zone by draining the macrotask queue until it is empty. The returned value is the milliseconds of time that would have been elapsed.
repo 在这里:https://stackblitz.com/github/felikf/angular-testing-examples
最佳答案
异步调度程序 是 setInterval
这是一个周期性的宏任务,目前是 flush() API 只刷新非周期性的宏任务,例如 setTimeout()
现在您应该使用 tick() 使其工作。
您可以阅读更多相关信息 here
关于使用 asyncScheduler 和 flush 进行 Angular Testing - 为什么它会因 flush() 而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649391/