简体   繁体   English

单元测试延迟加载模块路由

[英]Unit testing lazy loaded modules routing

I'm facing some problems with unit testing for routing.我在路由单元测试方面遇到了一些问题。 I've tried this solution, but this lazy loading notation is now deprecated , so my tests are failed for some reason.我已经尝试过这个解决方案,但是这个延迟加载符号现在弃用,所以我的测试由于某种原因失败了。 Could someone give me advice what might be wrong with my code?有人可以给我建议我的代码可能有什么问题吗?

app-routing.module.ts : app-routing.module.ts

export const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'files', loadChildren: () => import('./files/files.module').then(m => m.FilesModule)}, 
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

app-routing.module.spec.ts : app-routing.module.spec.ts

describe('AppRoutingModule', () => {
   let location: Location;
   let router: Router;
   let fixture;

   beforeEach(() => {
   TestBed.configureTestingModule({
       imports:[
           RouterTestingModule.withRoutes(routes),
           HttpClientModule,
           AboutComponent,
       ],
       declarations: [
           AppComponent,
           FilesComponent,
       ],
       providers: [{provide: APP_BASE_HREF, useValue: '/'}]
   })

   router = TestBed.get(Router);
   location = TestBed.get(Location);

   fixture = TestBed.createComponent(AppComponent);
   router.initialNavigation();
   });

   it('should navigate to files', fakeAsync(() => {
       const loader = TestBed.get(NgModuleFactoryLoader);
       loader.stubbedModules = {lazyModule : FilesModule }

       router.resetConfig([
           {path: 'files', loadChildren: 'lazyModule'},
       ]);

       router.navigate(['files']);
       tick(50);
       fixture.detectChanges();

       expect(location.path()).toBe('/files');
   }));
});

Thank you!谢谢!

Did you try:你试过了吗:

router.resetConfig([
  { path: 'files', loadChildren: () => Promise.resolve(FilesModule) },
 ]);

? ?

Or at this point it could be just an spy或者在这一点上它可能只是一个间谍

const spy = jasmine.createSpy('loadChildren');
...
router.resetConfig([
  { path: 'files', loadChildren: spy  },
 ]);
...
expect(spy).toHaveBeenCalled();

Not tested to so no idea if it will work.没有经过测试,所以不知道它是否有效。

You can use SpyNgModuleFactoryLoader in place of NgModuleFactoryLoader .您可以使用SpyNgModuleFactoryLoader代替NgModuleFactoryLoader

const loader = TestBed.get(SpyNgModuleFactoryLoader);
   loader.stubbedModules = {lazyModule : FilesModule }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM