Angular2 testing: What's the difference between a DebugElement and a NativeElement object in a ComponentFixture?

六月ゝ 毕业季﹏ 提交于 2019-12-02 15:04:16
  • nativeElement returns a reference to the DOM element
  • DebugElement is an Angular2 class that contains all kinds of references and methods relevant to investigate an element or component (See the source of DebugNode and DebugElement

to add on to what has been mentioned already :

  abstract class ComponentFixture {
  debugElement;       // test helper 
  componentInstance;  // access properties and methods
  nativeElement;      // access DOM
  detectChanges();    // trigger component change detection
}

source: https://github.com/angular/angular/blob/a7e9bc97f6a19a2b47b962bd021cb91346a44baa/modules/angular2/src/testing/test_component_builder.ts#L31

Take a look at Angular discussion about this topic and related PR.

Mainly:

fixture.componentInstance == fixture.debugElement.componentInstance;
fixture.nativeElement == fixture.debugElement.nativeElement;

.nativeElement() returns DOM tree whereas debugElement returns a JS object (debugElement tree). debugElement is a Angular's method.

.nativeElement() is Browser specific API that returns or give access to DOM tree. But what if application is running on non-browser platform (such as server or web-worker), in that case .nativeElement() may throw error.

If we are sure that our application will run on browser only, then unhesitantly we can use let el = fixture.nativeElement. But if we are not sure about the platform then to be on safer side use let le = fixture.debugElement because it returns a plain JS Object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!