Angular单元测试fixture.detectChanges()

简介: Angular单元测试fixture.detectChanges()

https://codecraft.tv/courses/angular/unit-testing/change-detection/


ATB:Angular Test Bed


// create component and test fixture

fixture = TestBed.createComponent(LoginComponent);


fixture通过ATB的createComponent方法创建,输入参数是正式的Component.


The fixture as well as holding an instance of the component also holds a reference to something called a DebugElement, this is a wrapper to the low-level DOM element that represents the component’s view, via the debugElement property.


通过fixture.debugElement获取Component view里的元素:

image.png

We can get references to other child nodes by querying this debugElement with a By class. The By class lets us query using a number of methods, one is via a CSS class like we have in our example, another way is to request by a type of directive like By.directive(MyDirective).


调用完query之后,如果不显式调用fixture.detectChanges, 则query返回的handle里,是无法获取到视图内容的。


That’s because when Angular first loads no change detection has been triggered and therefore the view doesn’t show either the Login or Logout text.


fixture is a wrapper for our component’s environment so we can control things like change detection.


fixture是Component环境的wrapper,因此在单元测试代码里,我们可以自行控制change detection的触发时机。


it('login button hidden when the user is authenticated', () => {

 expect(el.nativeElement.textContent.trim()).toBe('');

 fixture.detectChanges();

 expect(el.nativeElement.textContent.trim()).toBe('Login');

});


目录
相关文章
|
9月前
|
前端开发 测试技术
关于 fakeAsync 在 Angular 应用单元测试开发领域的使用介绍
关于 fakeAsync 在 Angular 应用单元测试开发领域的使用介绍
|
9月前
|
测试技术 开发者
关于 Angular testing 开发包里 fakeAsync 测试工具的用法
关于 Angular testing 开发包里 fakeAsync 测试工具的用法
|
弹性计算 编解码 资源调度
我与无影的初体验:使用无影云桌面进行一个开源 Angular 项目的端到端测试
近日很荣幸地收到了阿里云邀请做一个关于阿里旗下无影云桌面的评测,从官网上了解到阿里云无影云桌面原名为弹性云桌面,融合了无影产品技术后更名升级,可广泛应用于具有高数据安全管控、高性能计算等要求的安全办公、金融、设计、影视、教育等领域。
363 0
我与无影的初体验:使用无影云桌面进行一个开源 Angular 项目的端到端测试
|
Web App开发 编解码 资源调度
我与无影的初体验:使用无影云桌面进行一个开源 Angular 项目的端到端测试
一个 Angular 程序员与无影云桌面第一次亲密接触的体验。
我与无影的初体验:使用无影云桌面进行一个开源 Angular 项目的端到端测试
|
存储 测试技术 API
Angular 依赖的测试和 Fake
Angular 依赖的测试和 Fake
170 0
Angular 依赖的测试和 Fake
|
JavaScript 前端开发 测试技术
关于Angular里给Component protected方法写单元测试的技巧
关于Angular里给Component protected方法写单元测试的技巧
关于Angular里给Component protected方法写单元测试的技巧
|
Java 测试技术
如何在Angular单元测试里,对class protected方法进行测试
我的service class里有一个protected方法,我想在单元测试里对其进行测试:
如何在Angular单元测试里,对class protected方法进行测试
|
测试技术
Angular单元测试框架beforeEach和it的执行顺序
Angular单元测试框架beforeEach和it的执行顺序
Angular单元测试框架beforeEach和it的执行顺序