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

dgk*_*ane 59 javascript dom unit-testing jasmine angular

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

但是,在juliemr的Angular 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!');
    });
}));
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 47

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

  • `nativeElement`只在你想要调查DOM(属性,类,...设置或清除或可能调度DOM事件)时帮助你.当你想要研究Angular2应用程序的部分状态(组件,指令,......)时,你需要`DebugElement` (7认同)

can*_*idJ 22

添加到已经提到的内容:

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

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


Woj*_*tek 10

看一下关于这个主题和相关PR的Angular讨论.

主要是:

fixture.componentInstance == fixture.debugElement.componentInstance;
fixture.nativeElement == fixture.debugElement.nativeElement;
Run Code Online (Sandbox Code Playgroud)

  • 干杯,很有帮助。 (2认同)

小智 8

.nativeElement()返回 DOM 树,而debugElement返回一个 JS 对象(debugElement 树)。debugElement是 Angular 的方法。

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

如果我们确定我们的应用程序只能在浏览器上运行,那么我们可以毫不犹豫地使用let el = fixture.nativeElement. 但是如果我们不确定平台,那么为了更安全的使用,let le = fixture.debugElement因为它返回一个普通的 JS 对象。