angular - 角度测试中的 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');
}));
解决方案
它们相对于之前启动的异步操作做了不同的事情。例如; 调用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);
}));
推荐阅读
- javascript - 如何隐藏 Google API 密钥并仍然使用它
- apache-camel - 我在 apache camel 中处理 onException(真)的设计有问题
- android - 确定可用的生物识别硬件类型 Android
- python - Python - 使用 Plotly,有没有办法在放大气泡图时显示文本标签?
- java - JScrollPane 中一个位于另一个下方的按钮列表
- javascript - Web 组件转换发生得太晚
- html - `target="_blank"`和右键单击+`在新选项卡中打开链接`之间的Chrome差异
- swift - 相同的约束不同的结果
- sql - 应用程序的数据库结构向用户显示一次随机项目
- javascript - Windows:将 Webrtc 流提供给虚拟驱动程序