我正在尝试在我的组件上运行单元测试,这是我的路由器的输出。我已经对组件使用的路由器和服务进行了存根处理,我正在尝试使用 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; }
}