我想了解更多有关Angular2单元测试的信息。 目前,我无法获得组件html模板中特定元素的计数。
我的组件
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>
我的规范文件
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表达式设置为: 的期望(compiled.querySelector( 'DIV')的长度。).toEqual(5);
测试将始终返回true。
有没有人对如何在组件html模板中准确获取给定元素类型的计数有任何建议?
由于
答案 0 :(得分:1)
感谢您的建议。
虽然compiled.querySelector(&#39; div&#39;)没有回答(使用Angular Cli种子和vsCode)但它确实是一个缓存问题,因为我现在能够使用编译返回正确的元素数.querySelectorAll(&#39; DIV&#39)
我认为由于我最初尝试使用querySelectorAll的缓存而产生了混乱。
聚苯乙烯。我无法将任何评论作为答案设置,所以我必须自己设置答案。