如何为延迟加载模块编写单元测试用例
import { routes } from './app-routing';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
路线:导出const路线:路线= [{
小路: '',
重定向到:'家',
路径匹配:'完整'
},
{
路径:'家',
loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
},
{
路径:'qwe',
loadChildren: () => import('./path2/qwe.module').then(m => m.Qwemodule)
},
{
路径:'abc',
loadChildren: () => import('./path1/abc.module').then(m => m.Abcmodule)
}
];
规范文件:
describe('Routes', () => {
it(`should load 4 Routes`, async(() => {
console.log(routes.length.toString());
var a=routes.length;
expect(a).toEqual(4);
}));
});
describe('Routes load child', () => {
let location: Location;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
imports:[
RouterTestingModule.withRoutes(routes),
RouterTestingModule,
HttpClientModule,
HomeModule,
Qwemodule,
Abcmodule
],
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
});
});
it(`navigate to route /path loades module`, fakeAsync(() => {
router = TestBed.get(Router);
routes.forEach(route => {
location = TestBed.get(Location);
router.navigate([route.path]);
tick(50);
let t= route.loadChildren;
expect(route.loadChildren).not.toBeNull;
expect(location.path()).toBe('/'+route.path);
});
}));
});
它在 spc 中覆盖了路由器文件,但在代码覆盖率中未覆盖 loadchild,因此如何实现 100% 代码覆盖率是 20%
最佳答案
您应该为此使用 NgModuleFactoryLoader 和 Location 类
it('should navigate to lazy module', fakeAsync(() => {
let router = TestBed.get(Router);
router.initialNavigation();
//Used to load ng module factories.
let loader = TestBed.get(NgModuleFactoryLoader);
let location = TestBed.get(Location);
// sets up stubbedModules.
loader.stubbedModules = {
'./path/module_name.module#Your_lazymodule': Your_lazymodule,
};
router.resetConfig([
{ path: 'instructor', loadChildren: './path/module_name.module#Your_lazymodule' },
]);
router.navigateByUrl('/URL');
tick();
expect(location.path()).toBe('/URL');
}));
关于Angular 延迟加载模块,单元测试代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64440946/