angularunit-testingmodulelazy-loading

Angular version 18 - Alternate of SpyNgModuleFactoryLoader for unit testing of lazy loading Module


I am trying to write a unit test case for a lazy-loaded module with a canMatch guard. I have reviewed multiple threads on Stack Overflow, but the solutions provided are either outdated or not workable. The SpyNgModuleFactoryLoader option was deprecated in Angular version 13 and is no longer available in the latest version 18. Are there any alternative solutions for testing a lazy-loaded module with loadChildren?

enter image description here

enter image description here

it('should navigate to "auth" redirects you to /auth', async () => {
    store.dispatch(UserActions.loginSuccess({ data: MockData.UserLoggedIn }));
    router.navigate(['auth']).then(() => {
        expect(location.path()).toBe('/auth/dashboard');
    })
});

Solution

  • Here's how I do it in Angular 14, FWIW.

    In module:

    const routes: Routes = [
      {
       ...
          { path: 'myModule', loadChildren: () => 
              import('./myModule/myModule.module').then(m => m.MyModule) },
    ...
        ]
      }];
    

    and then in the UT:

      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [
            LoggerTestingModule, 
            RouterTestingModule,
          ],
        });
        router = TestBed.inject(Router);
      });
    
      it('should load MyModule when path is myModule', async () => {
        const { MyModule } = await import('./myModule/myModule.module');
        const config = router.config[0];
    
        if (config.children) {
          const x: (Route | undefined) = config.children.find(rc => rc.path === 'myModule');
          expect(await (x?.loadChildren?.())).toEqual(MyModule)
        }
      });