Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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

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?

like image 520
dgkane Avatar asked Jun 08 '16 14:06

dgkane


People also ask

What is the difference between debugElement and 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.

What is fixture debugElement?

DebugElement is an Angular class that contains all kinds of references and methods relevant to investigate an element as well as component fixture.debugElement.query(By.css('#shan'))

What is nativeElement in Angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

What is ComponentFixture Jasmine?

The ComponentFixture is a test harness for interacting with the created component and its corresponding element. Access the component instance through the fixture and confirm it exists with a Jasmine expectation: content_copy const component = fixture. componentInstance; expect(component).


1 Answers

  • 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
like image 146
Günter Zöchbauer Avatar answered Sep 22 '22 13:09

Günter Zöchbauer