angular 2 unit tests not able to find debugElement
Asked Answered
P

1

6

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; }
}
Polito answered 19/10, 2016 at 13:6 Comment(3)
What's null? The de?Maighdiln
Yes the de is NULLPolito
Is your component stable before you run your query? Try running fixture.isStable() and post the result.Dispensatory
W
3

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;
Warrin answered 15/2, 2018 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.