angular 2 unit tests not able to find debugElement
angular, angular2-testing, unit-testing
Solution
Before query the element call `fixture.detectChanges`
fixture = TestBed.createComponent(HeroesComponent);
comp = fixture.componentInstance;
//call detect changes here
fixture.detectChanges();
de = fixture.debugElement.query(By.css('*'));
console.log(de);
el = de.nativeElement;
Problem
I am trying to run unit tests on my component which is an output for my router. I have stubbed the router and service used by the component and I am trying to pull the element using the fixture.debugElement to confirm the tests are working. However this is always returning as NULL. Tests ``` import { TestBed, async, ComponentFixture } from '@angular/core/testing'; import { Router } from '@angular/router'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { HeroesComponent } from './heroes.component'; import { HeroService } from '../hero.service'; import { StubHeroService } from '../testing/stub-hero.service'; import { StubRouter } from '../testing/stub-router'; let comp: HeroesComponent; let fixture: ComponentFixture<HeroesComponent>; let de: DebugElement; let el: HTMLElement; describe('Component: Heroes', () => { beforeEach( async(() => { TestBed.configureTestingModule({ declarations: [HeroesComponent], providers: [ { provide: HeroService, useClass: StubHeroService }, { provide: Router, useClass: StubRouter } ] }) .compileComponents() .then(() => { fixture = TestBed.createComponent(HeroesComponent); comp = fixture.componentInstance; de = fixture.debugElement.query(By.css('*')); console.log(de); el = de.nativeElement; }); })); it('should create an instance', () => { expect(comp).toBeTruthy(); }); it('should update the selected hero', () => { comp.onSelect({ id: 0, name: 'Zero' }); fixture.detectChanges(); expect(el.querySelector('.selected').firstChild.textContent).toEqual(0); }); }); ``` Stubbed Router ``` export class StubRouter { navigateByUrl(url: string) { return url; } } ```