2016-06-17 131 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