Angular2测试:ComponentFixture中DebugElement和NativeElement对象之间的区别是什么?

时间:2016-06-08 14:37:04

标签: javascript unit-testing dom angular jasmine

我目前正在整理一些在组件级别上测试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!');
    });
}));

但是,在juliemr's Angular 2 test seed中,她通过父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!');
    });
}));

是否有任何特定情况你会在其nativeElement上使用fixture的debugElement.nativeElement?

4 个答案:

答案 0 :(得分:42)

  • nativeElement返回对DOM元素的引用
  • DebugElement是一个Angular2类,包含与调查元素或组件相关的所有类型的引用和方法(请参阅source of DebugNode and DebugElement

答案 1 :(得分:21)

添加已经提到的内容:

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

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

答案 2 :(得分:9)

查看Angular discussion about this topic及相关的PR

主要是:

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

答案 3 :(得分:3)

char desti[3]返回DOM树,而.nativeElement()返回JS对象(debugElement树)。 debugElement是Angular的方法。

debugElement是特定于浏览器的API,可返回或提供对DOM树的访问。但是,如果应用程序在非浏览器平台(例如服务器或Web工作者)上运行,在这种情况下,.nativeElement()可能会引发错误。

  

如果我们确定我们的应用程序只能在浏览器上运行,则   我们可以毫不犹豫地使用.nativeElement()。但是如果我们   不确定平台是否安全,请使用let el = fixture.nativeElement,因为它会返回纯JS对象。