单元测试 requestAnimationFrame 的方法有哪些?
requestAnimationFrame 与 setTimeout/setInterval 具有相同的性质。它也被 zone.js 修补,就像 fn 和 setTimeout 一样被修补。所以我首先想到的选择是
- 异步 + whenStable
- fakeAsync + 滴答(无效)
- fakeAsync + 刷新
- fakeAsync + 滴答(数字)
- setTimeout(1000) + 完成(茉莉花)
结果:
- async + whenStable :只是不工作
- fakeAsync + tick(void) :不工作
- fakeAsync + 刷新:不工作
- fakeAsync + tick(number) :有效(阅读下文)
- setTimeout(1000) + done (jasmine) : 不工作
这是方法:
reqAnimFrame() {
requestAnimationFrame(() => {
console.log('log stuff');
this.title = 'req frame title';
});
}
这是单元测试(工作单元测试):
it('fakeAsync', fakeAsync(function () {
const fixture = TestBed.createComponent(AppComponent);
const app: AppComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
app.reqAnimFrame();
tick(16);
expect(app.title).toBe('req frame title');
}));
幻数。16 是一个神奇的数字,例如 1000/60。它是帧大小。我只是通过实验发现了这个神奇的数字。
另外,当我写这个问题时,我想到了一个想法:也许,我可以以某种方式模拟 ng zone,并且所有通过它的代码都将被同步调用(我需要那个)。我还没试过这个。
UPD:经过一些研究 RAF 调用后,只需将任务放入宏任务区域队列。如何从测试中清除此队列?
那么我错过了什么?如何正确requestAnimationFrame
调用单元测试方法?