angular - FakeAsync/tick (Async/whenStable) 与 detectChanges()

标签 angular unit-testing asynchronous

你能帮我区分这两个东西吗。

根据我的理解,如果你只使用 observable,你可以使用 detectChanges()。因此,您可以直接更改组件属性或监视服务调用并返回一个可观察对象,然后调用 detectChanges(),更改将在 html 元素上可用。

但对于输入字段上的 [(ngModel)],您需要调用 tick() 才能在 html 元素上呈现更改。

所以如果我知道他们做什么以及何时使用什么,我会很棒。

提前致谢。

最佳答案

检测变化

detectChanges 方法在 ViewRef 上可用.

class ViewRef extends ChangeDetectorRef {
  // inherited from core/ChangeDetectorRef
  markForCheck(): void   <-----------------------------
  detach(): void
  detectChanges(): void
  checkNoChanges(): void
  reattach(): void
}

ViewRef 是组件的底层表示。当编写测试而不是 ViewRef 时,引入了另一个抽象,即 fixture:

fixture = TestBed.createComponent(BannerComponent);

它包裹了类似于ViewRef的组件。

detectChanges 方法为底层组件运行变更检测并执行以下操作:

  • 更新输入绑定(bind)属性
  • 更新DOM

还有很多其他的。

要了解更多信息,您可以阅读 Everything you need to know about change detection in Angular .因此,为了验证 DOM 中的更改或验证输入绑定(bind),您需要运行 detectChanges

打勾

Angular docs描述得很好:

The tick function is one of the Angular testing utilities and a companion to fakeAsync. You can only call it within a fakeAsync body.

Calling tick() simulates the passage of time until all pending asynchronous activities finish, including the resolution of the getQuote promise in this test case.

使用 ngModel 您需要调用它,因为在 ngModel 中创建的控件是异步注册的。这是来自 the article by Victor Savkin on forms 的引述:

To make it work, NgModel doesn’t add a form control synchronously — it does it in a microtask. In the example above, the three ngModels will schedule three microtasks to add the speaker, title, and highRating controls.

关于angular - FakeAsync/tick (Async/whenStable) 与 detectChanges(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342594/

相关文章:

node.js - 在恢复 package.json 包时出现 VS2015 中不允许的方法错误?

angular - 如何以编程方式在Ionic的variables.scss中设置变量?

c# - 无法设置 session 变量

visual-studio-2008 - 为什么在同一测试项目程序集中两次调用[AssemblyInitialize]和[AssemblyCleanup]?

postgresql - 如何在多个进程之间共享一组数据?

尽管传输存在,但 Python AsyncIO 由于缺少传输而无法创建协议(protocol)

animation - Angular 动画 : Page transition without style `position: absolute` ?

angular - 如何在其他延迟加载模块中使用模块中的组件

c# - 使用抽象测试类来运行单元和集成测试有什么值(value)吗?

python - 可以将 SQLAlchemy 配置为非阻塞吗?