2016-06-17 130 views
2

我想了解更多關於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模板中給定的元素類型的計數?

謝謝

+1

不知道這可能是'成功',但它應該是'querySelectorAll('div').length'。 – estus

+0

首先,請確保您遵循@estus建議,因爲querySelector只會返回1個沒有'length'屬性的結果。接下來,您是否在瀏覽器中禁用了緩存?開放式開發人員工具通常會對此有所幫助 – Sjoerd

+0

絕對是一個緩存問題。 'compiled.querySelector('div').length'會拋出一個異常。 – Michael

回答

1

謝謝您的建議。

雖然compiled.querySelector('div')沒有拋出一個答案(使用Angular Cli種子和vsCode),但確實是一個緩存問題,因爲我現在能夠使用compiled.querySelectorAll(' div')

我想我的混淆是由於緩存,因爲我最初嘗試querySelectorAll。

Ps。我無法將任何評論設置爲答案,因此我必須自行解答。

+0

您是否找到解決方案如何在測試中自動清除緩存? – nottinhill