对组件进行测试
对组件绑定的测试
例如在一个组件中,一个组件中模版里有一个标题的是
<h2 class='title'>{
{title}}</h2>
组件的类文件中对应绑定了一个类文件中的属性,
- 测试这个绑定的数据
it('should render title in a h2 tag ', () => {
const fixtureEle = TestBed.createComponent(EnvNewComponent);
fixtureEle.detectChanges();
const compiled = fixtureEle.nativeElement;
expect(compiled.querySelector('.title').textContent).toContain(component.title);
expect(compiled.querySelector('h2').textContent).toContain(component.title);
});
大体思路:
1. TestBed创建这个组件
通过 TestBed.createComponent() 方法创建出了当前的组件
2. 执行数据绑定
通过调用 fixture.detectChanges() 来要求 TestBed 执行数据绑定,才能获取到相应是数据绑定。
3. 查找元素
compiled.querySelector()是用来查找页面中的元素,可以根据标签、class属性值、等。
4. 断言判断
expect(compiled.querySelector(‘h2’).textContent).toContain(component.title);
查找出来的文字内容和组件中的属性进行比较是否一致。
需要注意的是TestBed.createComponent() 方法不会绑定数据,只有调用了detectChanges()才会进行数据绑定
查询具有某个属性的一系列元素使用:
compiled.querySelectorAll()
自动检测变更
在测试文件中,经常需要调用 detectChanges() ,这样有时会出现遗漏或者书写繁琐的问题,现在可以让Angular 测试环境自动运行变更检测。在这里可以使用 ComponentFixtureAutoDetect 服务提供商来配置 TestBed 就可以做到这一点
TestBed.configureTestingModule({
imports: [
NgZorroAntdModule,
TableModule,
RouterTestingModule,
SearchTableModule,
HttpClientTestingModule,
TranslateModule.forRoot()],
declarations: [EnvNewComponent, BreadcrumbStubComponent],
providers: [
TranslateService,
{
provide: ComponentFixtureAutoDetect, useValue: true}
],
schemas: [NO_ERRORS_SCHEMA]
})
- 自动检测变更的局限性</