Jasmine 框架将是一个不错的选择。以下测试示例可以扩展到您的应用程序,以确保正确完成从一个组件到另一个组件的路由(@angular/router 3.4.7)。
我最近在我的个人博客上写了一篇关于这个的文章:https://medium.com/burak-tasci/using-jasmine-framework-to-test-angular-router-b568a232efed
首先,让我们导入我们在这个测试中需要的依赖项:
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { Component, NgModule } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
然后,让我们创建一个包含router-outlet 的TestBootstrapComponent - 用于引导测试应用程序;和TestComponent。
您无需为每条路线创建不同的组件。一个虚拟测试组件就足够了。
@Component({ template: '<router-outlet></router-outlet>' })
export class TestBootstrapComponent {}
@Component({ template: '' })
export class TestComponent {}
现在,您需要将这些组件导入应用程序。
请记住,组件只能由一个模块导入,您应该创建一个 shared module 并在那里导入组件 - 如果需要,可以由任何 feature modules 导入:
@NgModule({
declarations: [TestComponent,TestBootstrapComponent],
imports: [RouterTestingModule]
})
export class TestSharedModule { }
然后,您需要提供routes:
export const testRoutes: Routes = [
{
path: '',
children: [
{
path: '',
component: TestComponent
},
{
path: 'about',
component: TestComponent
}
]
},
{
path: 'change-language/:languageCode',
component: TestComponent
},
{
path: '**',
redirectTo: '',
pathMatch: 'full'
}
];
最后,是时候为测试目的准备模块配置了:
// test module configuration for each test
export const testModuleConfig = () => {
// reset the test environment before initializing it.
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
.configureTestingModule({
imports: [
TestSharedModule,
RouterTestingModule.withRoutes(testRoutes),
]
});
};
毕竟,测试跨页面的路线导航就像下面这样简单:
describe('Some service',
() => {
beforeEach(() => {
testModuleConfig();
});
it('should be able to navigate to `/`',
fakeAsync(() => {
const injector = getTestBed();
const router = injector.get(Router);
const fixture = TestBed.createComponent(TestBootstrapComponent);
fixture.detectChanges();
// initial navigation
router.navigate(['/'])
.then(() => {
expect(router.url).toEqual('/');
});
}));
});