Javascript 角度2测试:什么';ComponentFixture中的DebugElement和NativeElement对象之间的区别是什么?
我目前正在整理一些最佳实践,以便在组件级别测试Angular 2应用程序 我已经看过一些教程,它们查询fixture的NativeElement对象中的选择器等Javascript 角度2测试:什么';ComponentFixture中的DebugElement和NativeElement对象之间的区别是什么?,javascript,unit-testing,dom,angular,jasmine,Javascript,Unit Testing,Dom,Angular,Jasmine,我目前正在整理一些最佳实践,以便在组件级别测试Angular 2应用程序 我已经看过一些教程,它们查询fixture的NativeElement对象中的选择器等 it('单击后应呈现“Hello World!”),异步(()=>{ createAsync(HelloWorld).then((fixture:ComponentFixture)=>{ fixture.detectChanges(); 设el=fixture.nativeElement; el.querySelector('h1')
it('单击后应呈现“Hello World!”),异步(()=>{
createAsync(HelloWorld).then((fixture:ComponentFixture)=>{
fixture.detectChanges();
设el=fixture.nativeElement;
el.querySelector('h1')。单击();
fixture.detectChanges();
expect(el.querySelector('h1')).toHaveText('helloworld!');
});
}));代码>看一看和相关的
主要是:
fixture.componentInstance == fixture.debugElement.componentInstance;
fixture.nativeElement == fixture.debugElement.nativeElement;
nativeElement
返回对DOM元素的引用
DebugElement
是一个Angular2类,它包含与调查元素或组件相关的各种引用和方法(请参见
要补充前面提到的内容:
abstract class ComponentFixture {
debugElement; // test helper
componentInstance; // access properties and methods
nativeElement; // access DOM
detectChanges(); // trigger component change detection
}
来源:.nativeElement()
返回DOM树,而debugElement
返回JS对象(debugElement树)。debugElement
是Angular的方法
.nativeElement()
是特定于浏览器的API,用于返回或访问DOM树。但如果应用程序在非浏览器平台(如服务器或web worker)上运行,在这种情况下,.nativeElement()
可能会引发错误
如果我们确信我们的应用程序将只在浏览器上运行,那么
我们可以毫不犹豫地使用let el=fixture.nativeElement
如果您不确定平台是否安全,请使用let le=
debugElement
,因为它返回一个普通的JS对象
干杯-因此,我想如果我没有使用除nativeElement之外的任何DebugElement成员,那么使用componentFixture.nativeElement可能更容易阅读。nativeElement
仅在您想要调查DOM(是属性、类、…设置或清除还是分派DOM事件)时才有帮助。当您想要调查Angular2应用程序部分(组件、指令等)的状态时,您需要DebugElement
Cheers,非常有用。