有哪些方法可以对requestAnimationFrame进行单元测试?
requestAnimationFrame与setTimeout/setInterval具有相同的性质,也像setTimeout这样的函数一样被zone.js打补丁。所以我首先想到的选项是:
- async + whenStable
- fakeAsync + tick(void)
- fakeAsync + flush
- fakeAsync + tick(number)
- setTimeout(1000) + done (jasmine)
结果如下:
- async + whenStable:根本不起作用
- fakeAsync + tick(void):不起作用
- fakeAsync + flush:不起作用
- 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区域,所有通过它的代码都将被同步调用(我需要这样)。我还没有尝试过。
更新:经过一些研究,RAF调用只是将任务放入宏任务区队列中。如何从测试中清空此队列?
那么我错过了什么? 如何正确地对具有requestAnimationFrame
调用的方法进行单元测试?