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

dgkane picture dgkane · Jun 8, 2016 · Viewed 31.8k times · Source

I'm currently putting together some best practices for testing Angular 2 apps on a component level.

I've seen a few tutorials query a fixture's NativeElement object for selectors and the like, e.g.

However, in juliemr's Angular 2 test seed she accesses the NativeElement through a parent DebugElement object.

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!');
    });
}));

Are there any specific cases you'd use a fixture's debugElement.nativeElement over its nativeElement?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jun 8, 2016
  • 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