8

单元测试 requestAnimationFrame 的方法有哪些?

requestAnimationFrame 与 setTimeout/setInterval 具有相同的性质。它也被 zone.js 修补,就像 fn 和 setTimeout 一样被修补。所以我首先想到的选择是

  1. 异步 + whenStable
  2. fakeAsync + 滴答(无效)
  3. fakeAsync + 刷新
  4. fakeAsync + 滴答(数字)
  5. setTimeout(1000) + 完成(茉莉花)

结果:

  1. async + whenStable :只是不工作
  2. fakeAsync + tick(void) :不工作
  3. fakeAsync + 刷新:不工作
  4. fakeAsync + tick(number) :有效(阅读下文)
  5. 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调用单元测试方法?

4

1 回答 1

3

tick(16)是正确的,因为requestAnimationFrameinfakeAsync只是一个16ms delay macroTask.

如果你想刷新fakeAsync,只需调用flush(),刷新也是从@angular/core/testing.

于 2018-06-05T16:26:32.087 回答