Cómo escribir una prueba unitaria para enrutamiento de Angular con guardacanales canActivate.
¿Cómo escribir una prueba unitaria para la ruta angular con la guarda canActivate? Estoy obteniendo el siguiente error si uso la guarda canActivate en las rutas. Si no, no está lanzando ningún error y pasando la prueba. Por favor, ayúdame con un ejemplo adecuado y también con una explicación.
app-routing.module.ts
js
export const routes: Routes = [
{ path: ”, component: LoginComponent },
{ path: ‘home’, canActivate: [AuthGuard], component: HomeComponent },
{ path: ‘**’, redirectTo: ‘/home’ }
]
auth-guard.guard.ts
export class AuthGuard implements CanActivate {
private auth: IAuth;
constructor(
private storageService: StorageService,
private router: Router
){}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean |="" urltree=""> | Promise<boolean |="" urltree=""> | boolean | UrlTree {
this.auth = JSON.parse(this.storageService.getLocalStorageItem('auth'));
if(this.auth){
return true;
}
this.router.navigate(['/'], {queryParams: {returnUrl: state.url}});
return false;
}
}
app-routing.module.test.ts
js
test(Navigate to 'home' takes you to /home
, fakeAsync(() => {
router.navigate([‘/home’]).then(() => {
expect(location.path()).toEqual(‘/home’);
});
flush();
}));
Resultado de la prueba
“`
Testing Router › Navigate to 'home' takes you to /home
Uncaught (in promise): Error: expect(received).toEqual(expected) // deep equality
Expected: "/home"
Received: "/"
Error: expect(received).toEqual(expected) // deep equality
“`
davy.ai
Para escribir una prueba unitaria para el enrutamiento de Angular con una guarda de canActivate, puedes usar los servicios
RouterTestingModule
yRouter
para simular la navegación y comprobar el resultado esperado.Por ejemplo, puedes utilizar el siguiente código para probar la guarda
canActivate
: