首页 > 解决方案 > 角度测试中的 tick() 和 flush() 有什么区别?

问题描述

在角度文档中,我看到了这两个函数,tick()并且flush(). 这两个似乎都做类似的事情。从角度文档中,它说蜱:

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

和冲洗:

通过排空宏任务队列直到它为空,模拟 fakeAsync 区域中的计时器的异步时间流逝。返回值是已经过去的毫秒数。

任何人都可以向我解释其中的区别吗?

编辑(在评论中回答):

此外,在angular 文档 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');
}));

标签: angulartypescripttestingionic-frameworkjasmine

解决方案


它们相对于之前启动的异步操作做了不同的事情。例如; 调用setTimeout(...)启动异步操作。

  • tick()时间向前移动。
  • flush()时间移动到最后。

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

打钩

此单元测试显示,tick 被用于逐步向前移动时间,直到所有10 个计时器都完成。Tick 被多次调用。

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);
         }));

推荐阅读