[英]Angular2 unit test component
I'm learning new features and changes in Angular 2.0.0 version. 我正在学习Angular 2.0.0版本中的新功能和更改。 I have the problem with getting text content for HTML element inside the testing component. 我在获取测试组件内HTML元素的文本内容时遇到问题。
this is my component which I want to test 这是我要测试的组件
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);
}
}
and this is the unit test for that component 这是该组件的单元测试
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 returns 'title' but title.textContent is empty Fixture.componentInstance.note.title返回'title',但title.textContent为空
any idea what might went wrong? 知道可能出了什么问题吗?
I found that I need to call fixture.detectChanges()
to get current state of component template 我发现我需要调用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 ''
});
})); }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.