Angular Lazy加载模块,单元测试代码覆盖率

问题描述

如何为延迟加载模块编写单元测试用例

import { routes } from './app-routing';
@NgModule({
    imports: [RouterModule.forRoot(routes)],exports: [RouterModule]
})
export class AppRoutingModule { }

route:export const路由:Routes = [ { 路径:“, redirectTo:'home', pathMatch:“已满” }, { 路径:“家”, 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');
  }));