您必须引导您的测试,包括路由器模块。这与引导应用程序非常相似:
const IMPORTS: any[] = [
BrowserModule,
...
RouterModule.forRoot(routes)
];
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: IMPORTS,
declarations: DECLARATIONS
providers: PROVIDERS
}).compileComponents();
}));
然后,您可以获得对路由器的引用。
beforeEach(() => {
router = TestBed.get(Router);
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
});
测试状态(需要依赖,因为组件被渲染等等):
it('routes to the dummy component', fakeAsync(() => {
tick(1000);
fixture.detectChanges();
router.navigate(['dummy']);
tick(1000);
fixture.detectChanges();
expect(router.isActive('/dummy', true)).toBe(true);
}));
测试通信(不路由;我们只需要验证导航是否真的发生):
it('routes to the dummy component', fakeAsync(() => {
spyOn(router, 'navigate').and.callFake(() => {});
tick(1000);
fixture.detectChanges();
router.navigate(['dummy']);
tick(1000);
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['dummy']);
}));
在实际测试中,您不会测试 navigate() 方法。实际上,您将测试某种用户行为,例如单击:
在组件中(在本例中为 YourComponent):
onClick() {
this.router.navigate(['dummy']);
}
在测试中(通过点击触发器替换 navigate() ):
element.querySelector('button').click();