如果我们在组件控制器中注入 Route 服务,这里有一个例子:
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'; // Because we inject service in our component
import { Router } from '@angular/router'; // Just if we need to test Route Service functionality
import { AppComponent } from './app.component';
import { DummyLoginLayoutComponent } from '../../../testing/mock.components.spec'; // Because we inject service in your component
describe('AppComponent', () => {
let router: Router; // Just if we need to test Route Service functionality
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
DummyLoginLayoutComponent // Because we inject service in our component
],
imports: [
RouterTestingModule.withRoutes([
{ path: 'login', component: DummyLoginLayoutComponent },
]) // Because we inject service in our component
],
}).compileComponents();
router = TestBed.get(Router); // Just if we need to test Route Service functionality
router.initialNavigation(); // Just if we need to test Route Service functionality
}));
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 { }