Angular2ユニットのテストの詳細を理解しようとしています。 現在、コンポーネントhtmlテンプレート内の特定の要素の数を取得できません。Angular2コンポーネントのユニットテスト
コンポーネントの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 { 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() {
}
}
マイコンポーネント
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
まず、querySelectorは 'length'プロパティを持たない1つの結果を返すだけなので、@estusのアドバイスに従ってください。次に、ブラウザでキャッシングを無効にしましたか?開いている開発者ツールは、通常、これに役立ちます。 – Sjoerd
明らかにキャッシュ問題です。 'compiled.querySelector( 'div')。length'は例外をスローします。 – Michael