如果我们在组件控制器中注入Route服务,这里就是一个例子:
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { AppComponent } from './app.component';
import { DummyLoginLayoutComponent } from '../../../testing/mock.components.spec';
describe('AppComponent', () => {
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
DummyLoginLayoutComponent
],
imports: [
RouterTestingModule.withRoutes([
{ path: 'login', component: DummyLoginLayoutComponent },
])
],
}).compileComponents();
router = TestBed.get(Router);
router.initialNavigation();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
我们还可以测试其他功能,例如navigate()
。以防万一:
it('should call eventPage once with /register path if event is instanceof NavigationStart', fakeAsync(() => {
spyOn(analyticService, 'eventPage');
router.navigate(['register'])
.then(() => {
const baseUrl = window.location.origin;
const url = `${baseUrl}/register`;
expect(analyticService.eventPage).toHaveBeenCalledTimes(1);
expect(analyticService.eventPage).toHaveBeenCalledWith(url);
});
}));
我的文件包含所有模拟组件(mock.components.specs.ts)
import { Component } from '@angular/core';
@Component({
selector: 'home',
template: '<div>Dummy home component</div>',
styleUrls: []
})
export class DummyHomeComponent { }
router = TestBed.get(Router)
我的路由器保存到夹具旁边一个变量,而不是铸造部件的任何作为推荐angular.io/guide/testing#testbedget