您必須引導您的測試,包括路由器模塊。這與引導應用程序非常相似:
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']);
}
在試驗(通過點擊觸發替換引導()):
element.querySelector('button').click();