Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 unit tests not able to find debugElement

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; }
}
like image 781
Paul Mooney Avatar asked Oct 30 '22 18:10

Paul Mooney


1 Answers

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;
like image 189
Nilmi Nawalage Avatar answered Nov 15 '22 07:11

Nilmi Nawalage