【问题标题】:Angular Lazy loading module ,unit test code coverageAngular 延迟加载模块,单元测试代码覆盖率
【发布时间】:2021-02-03 00:47:12
【问题描述】:

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

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

route :export const routes: Routes = [ { 小路: '', 重定向到:'家', 路径匹配:'完整' }, { 路径:'家', 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%

【问题讨论】:

    标签: angular unit-testing lazy-loading code-coverage karma-coverage


    【解决方案1】:

    你应该为此使用 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');
      }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 2020-01-27
      • 2012-01-18
      • 2021-06-14
      • 2023-04-07
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多