Angular2测试: 在 Component Fixture 中 DebugElement 和 NativeElement 对象之间有什么区别?

我目前正在整合一些最佳实践,以便在组件级别上测试 Angular 2应用程序。

我看到过一些教程查询 fixture 的 NativeElement 对象以获得选择器之类的东西,例如。

it('should render "Hello World!" after click', async(() => {
builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
fixture.detectChanges();
let el = fixture.nativeElement;
el.querySelector('h1').click();
fixture.detectChanges();
            

expect(el.querySelector('h1')).toHaveText('Hello World!');
});
}));

但是,在 朱利叶尔角2试验种子中,她通过父 DebugElement 对象访问 NativeElement。

it('should render "Hello World!" after click', async(() => {
builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
compiled.querySelector('h1').click();
fixture.detectChanges();
            

expect(compiled.querySelector('h1')).toHaveText('Hello World!');
});
}));

有没有什么特定的情况下,您会使用 fixture 的 deguElement.nativeElement 来代替它的 nativeElement?

40425 次浏览

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 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

.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.