2016-10-01 120 views
0

我正在学习Angular 2.0.0版本中的新功能和更改。我遇到了在测试组件中获取HTML元素的文本内容的问题。Angular2单元测试组件

这是我的分量我想测试

import { 
    Component, 
    Input, 
    Output, 
    EventEmitter 
} from '@angular/core'; 

@Component({ 
    selector: 'note-card', 
    template: ` 
    <div 
     class="note-card row shadow-1" 
     [ngStyle]="{'background-color': note.color}" 
     (mouseenter)="toggleCheck()" 
     (mouseleave)="toggleCheck()" 
    > 
     <div class="icon" *ngIf="showCheck" (click)="onChecked()"> 
     <i class="material-icons">check</i> 
     </div> 
     <div class="col-xs-12 title"> 
     {{ note.title }} 
     </div> 
     <div class="col-xs-12 value"> 
     {{ note.value }} 
     </div> 
    </div> 
    ` 
}) 
export class NoteCard { 
    @Input() note = {}; 
    @Output() checked = new EventEmitter(); 

    showCheck: boolean = false; 

    toggleCheck() { 
    this.showCheck = !this.showCheck; 
    } 

    onChecked() { 
    this.checked.next(this.note); 
    } 
} 

,这是该组件

import { 
    inject, 
    async, 
    TestBed, 
    ComponentFixture, 
} from '@angular/core/testing'; 
import { By } from '@angular/platform-browser'; 

import { Component } from '@angular/core'; 
import { NoteCard } from './note-card'; 

@Component({ 
    selector: 'note-card-test', 
    template: '<note-card [note]="note"></note-card>' 
}) 
class TestComponent { 
    note = { 
    value: 'note', 
    title: 'title', 
    color: 'red', 
    id: 1 
    } 
} 

describe('Note card',() => { 
    beforeEach(() => TestBed.configureTestingModule({ 
    declarations: [TestComponent, NoteCard] 
    })); 

    it('should have correct title', async(() => { 
    let fixture = TestBed.createComponent(TestComponent); 


    fixture.whenStable().then(() => { 
     const title = <HTMLElement>fixture.debugElement.query(By.css('.title')).nativeElement; 

     console.log(fixture.componentInstance.note.title); // returns 'title' 
     console.log(title); // return html element with empty text content 
     expect(title.textContent.trim()).toEqual('title'); // failed, title.textContent.trim() is equal to '' 
    }); 
    })); 
}); 

fixture.componentInstance.note.title回报“标题” 但标题单元测试.textContent为空

任何想法可能会出错?

回答

0

我发现我需要调用fixture.detectChanges()获得组件模板的当前状态

it('should have correct title', async(() => { 
let fixture = TestBed.createComponent(TestComponent); 


fixture.whenStable().then(() => { 
    const title = <HTMLElement>fixture.debugElement.query(By.css('.title')).nativeElement; 

    fixture.detectChanges(); 

    console.log(fixture.componentInstance.note.title); // returns 'title' 
    console.log(title); // return html element with empty text content 
    expect(title.textContent.trim()).toEqual('title'); // failed, title.textContent.trim() is equal to '' 
}); 

}));