Hoa*_*Son 7 testing unit-testing angular-cli angular
在这个示例测试文件中,我看到了两种不同的语法
一个是const app = fixture.debugElement.componentInstance;,另一个是const compiled = fixture.nativeElement;我不知道这两种语法有什么不同?
我对角度测试完全陌生,我正在将它应用到我的项目中,但对此我有点困惑。
describe('AppComponent (initial CLI version)', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
}));
});
Run Code Online (Sandbox Code Playgroud)
小智 15
DebugElement是一个跨原生元素和测试组件的包装器,允许测试在所有支持的平台上运行。
fixture.nativeElement和fixture.debugElement.nativeElement是一样的东西。这是由 Angular 在 DOM 中生成的 HTML 元素,如被测试组件的模板中所指定。通过nativeElement您可以访问和测试屏幕上显示的内容,在您的测试中上面的文本内容是否H1为Welcome to the app. 请记住,fixture.debugElement还有其他在测试中很有用的方法和属性,例如By.css()。
fixture.componentInstance使您可以访问组件类。这允许您测试组件的公共 API。在上面的测试中,您的应用组件的 title 属性是否为app.
您可以查看Angular 的测试指南以获取更多详细信息。
| 归档时间: |
|
| 查看次数: |
3988 次 |
| 最近记录: |