我想了解更多关于Angular2单元测试的内容。 目前我无法获得我的组件html模板中特定元素的计数。Angular2组件单元测试
我的组件
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'cl-header',
templateUrl: 'cl-header.component.html',
styleUrls: ['cl-header.component.css']
})
export class ClHeaderComponent implements OnInit {
headerTitle: string = 'Some Title';
constructor() {}
ngOnInit() {
}
}
组件的HTML模板
<nav class="navbar navbar-default" role="navigation">
<ul class="nav navbar-nav">
<li><a href="#" class="fa fa-bars fa-2x"></a></li>
<li><a href="http://localhost:91/UserHome/" class="fa fa-home fa-2x no-padding"></a></li>
</ul>
<div class="nav navbar-text-center">{{headerTitle}}</div>
<a href="#" class="navbar-brand pull-right">
<img src="app/components/cl-header/shared/logo.png" height="28px" alt="logo" />
</a>
<i>testtext</i>
</nav>
我的SPEC文件
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
injectAsync
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { ClHeaderComponent } from './cl-header.component';
describe('Component: ClHeader',() => {
it('should display header title: "Some Title"', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(ClHeaderComponent).then((fixture) => {
fixture.detectChanges();
var compiled = fixture.debugElement.nativeElement;
//WORKING
//To check that a given piece of text exists in the html template
//expect(compiled.innerHTML).toContain('ul');
//To check whether a given element type contains text
//expect(compiled.querySelector('div')).toHaveText('Some Title');
//END WORKING
//NOT WORKING - ALWAYS RETURNS SUCCESS NO MATTER WHAT THE TOEQUAL COUNT IS
//To check that a given element by type exists in the html template
expect(compiled.querySelector('div').length).toEqual(5);
});
}));
});
无论我如何设置toEqual表达式如下: expect(compiled.querySelector('div').length).toEqual(5);
测试将始终返回true。
有没有人有任何建议如何准确得到组件html模板中给定的元素类型的计数?
谢谢
不知道这可能是'成功',但它应该是'querySelectorAll('div').length'。 – estus
首先,请确保您遵循@estus建议,因为querySelector只会返回1个没有'length'属性的结果。接下来,您是否在浏览器中禁用了缓存?开放式开发人员工具通常会对此有所帮助 – Sjoerd
绝对是一个缓存问题。 'compiled.querySelector('div').length'会抛出一个异常。 – Michael