角度测试中tick()和flush()有什么区别?

时间:2019-06-07 17:23:18

标签: angular typescript testing ionic-framework jasmine

在角度文档中,我看到了tick()flush()这两个函数。两者似乎都做类似的事情。从角度文档中,它会打勾:

  

为fakeAsync区域中的计时器模拟异步时间流逝。

冲洗:

  

通过耗尽宏任务队列直到其为空来模拟fakeAsync区域中计时器的异步时间流逝。返回的值是经过的毫秒数。

有人可以向我解释差异吗?

编辑(在评论中回答):

此外,在angular documentation tick()中使用时不带参数,并且该行上的注释甚至使用了短语“ flush”

it('should display error when TwainService fails', fakeAsync(() => {
  // tell spy to return an error observable
  getQuoteSpy.and.returnValue(
    throwError('TwainService test failure'));

  fixture.detectChanges(); // onInit()
  // sync spy errors immediately after init

  tick(); // flush the component's setTimeout()

  fixture.detectChanges(); // update errorMessage within setTimeout()

  expect(errorMessage()).toMatch(/test failure/, 'should display error');
  expect(quoteEl.textContent).toBe('...', 'should show placeholder');
}));

1 个答案:

答案 0 :(得分:3)

相对于先前启动的异步操作,它们执行不同的操作。例如;调用setTimeout(...)将启动异步操作。

  • tick()向前移动时间
  • flush()时间移到末尾。

通过这些功能的单元测试可以更好地说明这一点。

勾选

此单元测试显示了滴答声正在用于逐步向前移动时间,直到所有 10 计时器结束。刻度线被多次调用。

https://github.com/angular/angular/blob/master/packages/core/test/fake_async_spec.ts#L205


      it('should clear periodic timers', fakeAsync(() => {
           let cycles = 0;
           const id = setInterval(() => { cycles++; }, 10);

           tick(10);
           expect(cycles).toEqual(1);

           discardPeriodicTasks();

           // Tick once to clear out the timer which already started.
           tick(10);
           expect(cycles).toEqual(2);

           tick(10);
           // Nothing should change
           expect(cycles).toEqual(2);
         }));

冲洗

此单元测试表明,所有异步任务在返回时都应完成,并且返回的值告诉您完成它们需要多长时间。

https://github.com/angular/angular/blob/master/packages/core/test/fake_async_spec.ts#L273

      it('should flush multiple tasks', fakeAsync(() => {
           let ran = false;
           let ran2 = false;
           setTimeout(() => { ran = true; }, 10);
           setTimeout(() => { ran2 = true; }, 30);

           let elapsed = flush();

           expect(ran).toEqual(true);
           expect(ran2).toEqual(true);
           expect(elapsed).toEqual(30);
         }));
相关问题