在这个示例测试文件中,我看到了两种不同的语法
一个是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!');
}));
});发布于 2019-06-08 16:29:02
DebugElement是一个跨本机元素和测试组件的包装器,允许测试在所有支持的平台上运行。
fixture.nativeElement和fixture.debugElement.nativeElement是一回事。这是由Angular在DOM中生成的HTML元素,在测试组件的模板中指定。通过nativeElement,您可以访问和测试屏幕上可视化的内容,在上面的测试中,H1的文本内容是否为Welcome to the app。请记住,例如,在By.css()这样的测试中,fixture.debugElement还有其他有用的方法和属性。
fixture.componentInstance使您可以访问component类。这允许您测试组件的公共API。在上面的测试中,您将检查应用程序组件的title属性是否为app。
您可以查看Angular's testing guide以了解更多详细信息。
https://stackoverflow.com/questions/56487593
复制相似问题