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?
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.
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'))
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.
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).
nativeElement
returns a reference to the DOM elementDebugElement
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 If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With