ng-mocks icon indicating copy to clipboard operation
ng-mocks copied to clipboard

Cover all guards variants

Open satanTime opened this issue 2 years ago • 0 comments

The question came from gitter: https://gitter.im/ng-mocks/community?at=6128e79d4c7be06b7986702b

Hi guys. I'm trying to test a route resolver and everything seems to be working fine for the successful resolve, but for unsuccessful resolves, I redirect the user to a different route using

            return from(
                this.router.navigate(['app/maintenance'], { state: { tab } })
            ).pipe(map(() => null));

The problem seems to be that when I check the location.path, it has not navigated to the route yet (Error: Expected '/' to equal '/app/maintenance'). I can also see in coverage that the map operator has not been hit at all, which leads me to believe that the router.navigate promise has not resolved yet when the test ends. I've tried multiple tick, flush, flushMicrotasks calls but I'm not able to get this router navigate to resolve. Can anyone assist with this?


One thing I noticed is that the route has a guard on, and to get the tests to run I had to mock that guard, even though I'm adding .exclude(NG_MOCKS_GUARDS).

Here is my MockBuilder

return MockBuilder(WidgetResolver, [
    RuntimeModule,
    AppModule,
    MaintenanceModule,
    HomeModule,
    StoreFeaturesModule
])
    .exclude(NG_MOCKS_GUARDS)
    .keep(RouterModule)
    .keep(RouterTestingModule.withRoutes([]))
    .keep(RuntimeComponent)
    .keep(StoreRootModule)
    .mock(WidgetPreviewComponent)
    .mock(MaintenanceComponent)
    .mock(MessageService)
    .mock(MaintenanceGuard)
    .provide(provideMockStore({ initialState }));

If I don't mock that guard then I get

Error: Uncaught (in promise): TypeError: Cannot read property 'pipe' of undefined TypeError: Cannot read property 'pipe' of undefined at MaintenanceGuard.checkForMaintenancePermission (src/app/guards/maintenance.guard.ts:34:51) at MaintenanceGuard.canLoad (src/app/guards/maintenance.guard.ts:22:6)

Does the NG_MOCKS_GUARDS work for canLoadGuards?

satanTime avatar Aug 30 '21 06:08 satanTime