我试图编写一个简单的单元测试,但无法编译我的模板。 AppComponent
有一个名为text
的变量,该变量呈现为h1
标记。在测试html时,它总是以''
的形式返回。有谁知道我在这里失踪了什么?
测试代码
import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import {AppComponent} from './app.component';
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
const mainTitle = 'Angular Unit Testing';
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
}));
it(`should render ${mainTitle} to an H1 tag`, async(() => {
const compiled = fixture.debugElement.nativeElement;
console.log('here', compiled.querySelector('h1'));
expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
}));
});
组件代码
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
text = 'Angular Unit Testing';
}
HTML
<h1>{{text}}</h1>
答案 0 :(得分:2)
您必须设置仅限组件的“text”公共属性,然后它将在h1标签
中呈现it(`should render ${mainTitle} to an H1 tag`, async(() => {
const compiled = fixture.debugElement.nativeElement;
component.text = 'Angular Unit Testing';
fixture.detectChanges();
expect(compiled.querySelector('h1').textContent).toEqual(mainTitle);
}));