Cesar Elías Armendariz Ruano
EstudianteAhora haremos pruebas de integración con las funcionalidades de guardianes, ya que probaremos la integración de los guardianes desde una ruta a otra
primero cambiamos un poco el comportamiento del auth guard
auth.guard.ts
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return this.authService.getUser() .pipe( map(user => { if(!user) { this.router.navigate(['/']); return false; } return true; }) )
Ingresamos el guardian en la ruta de others component
app-routing.module.ts
import { AuthGuard } from './guards/auth.guard'; export const routes: Routes = [ { path: 'others', canActivate: [AuthGuard], component: OthersComponent }, ];
Ahora podemos hacer mockin de un usuario y probar si logra entrar o no con el guardian activo
app.integration.spec.ts
import { AuthService } from './services/auth.service'; import { generateOneUser } from './models/user.mock'; describe('App Integration test', () => { let authService: jasmine.SpyObj<AuthService>; beforeEach(async () => { const authServiceSpy = jasmine.createSpyObj('AuthService', ['getUser']); await TestBed.configureTestingModule({ imports: [ AppModule, RouterTestingModule.withRoutes(routes) ], providers: [ { provide: AuthService, useValue: authServiceSpy } ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); }); it('should render OthersComponent when clicked with session', fakeAsync(() => { const productsMocks = generateManyProducts(10); productService.getAll.and.returnValue(asyncData(productsMocks)); const userMock = generateOneUser(); authService.getUser.and.returnValue(mockObservable(userMock)); clickElement(fixture, 'others-link', true); tick(); // wait while nav... fixture.detectChanges(); // ngOnInit - OthersComponent tick(); fixture.detectChanges(); // ngOnInit - OthersComponent expect(router.url).toEqual('/others'); const element = query(fixture, 'app-others'); expect(element).not.toBeNull(); const text = getText(fixture, 'products-length'); expect(text).toContain(productsMocks.length.toString()); })); it('should render OthersComponent when clicked without session', fakeAsync(() => { authService.getUser.and.returnValue(mockObservable(null)); clickElement(fixture, 'others-link', true); tick(); // wait while nav... fixture.detectChanges(); // ngOnInit - OthersComponent tick(); fixture.detectChanges(); // ngOnInit - OthersComponent expect(router.url).toEqual('/'); }));