3
votes

How can I write unit test case for lazy loading Module

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

route :export const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) }, { path: 'qwe', loadChildren: () => import('./path2/qwe.module').then(m => m.Qwemodule) }, { path: 'abc', loadChildren: () => import('./path1/abc.module').then(m => m.Abcmodule) } ];

spec file:

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);
    });
   }));
});

It lodes the router file covers in spc but in code coverage loadchild is not covered so it is 20% how to achieve 100% code coverage

1

1 Answers

-1
votes

You should use NgModuleFactoryLoader and Location class for this

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');
  }));