es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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

“`

Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Para escribir una prueba unitaria para el enrutamiento de Angular con una guarda de canActivate, puedes usar los servicios RouterTestingModule y Router para simular la navegación y comprobar el resultado esperado.

    Por ejemplo, puedes utilizar el siguiente código para probar la guarda canActivate:

    import { TestBed, async, fakeAsync, tick } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { Router } from '@angular/router';
    import { AuthGuard } from './auth-guard.guard';
    import { StorageService } from './storage.service';
    
    describe('AuthGuard', () => {
      let authGuard: AuthGuard;
      let router: Router;
      let storageService: StorageService;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [RouterTestingModule],
          providers: [AuthGuard, StorageService]
        });
    
        authGuard = TestBed.get(AuthGuard);
        router = TestBed.get(Router);
        storageService = TestBed.get(StorageService);
      });
    
      it('should be created', () => {
        expect(authGuard).toBeTruthy();
      });
    
      it('should return true if user is authenticated', fakeAsync(() => {
        spyOn(storageService, 'getLocalStorageItem').and.returnValue(JSON.stringify({}));
        const result = authGuard.canActivate(null, null);
        tick();
        expect(result).toBeTruthy();
      }));
    
      it('should return false if user is not authenticated', fakeAsync(() => {
        spyOn(storageService, 'getLocalStorageItem').and.returnValue(null);
        const result = authGuard.canActivate(null, null);
        tick();
        expect(result).toBeFalsy();
      }));
    });
    

Comments are closed.