#unit-testing #angular #angular2-testing
#модульное тестирование #angular #angular2-тестирование
Вопрос:
Я пытаюсь запустить модульные тесты на своем компоненте, который является выходом для моего маршрутизатора. Я отключил маршрутизатор и службу, используемые компонентом, и пытаюсь извлечь элемент с помощью fixture.debugElement, чтобы подтвердить, что тесты работают. Однако это всегда возвращается как NULL.
Тесты
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);
});
});
Заглушенный маршрутизатор
export class StubRouter {
navigateByUrl(url: string) { return url; }
}
Комментарии:
1. Что такое null?
de
?2. Да,
de
равно нулю3. Стабилен ли ваш компонент перед выполнением запроса? Попробуйте запустить fixture.isStable() и опубликовать результат.
Ответ №1:
Перед запросом вызов элемента 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;