|
| 1 | +import { TestBed } from '@angular/core/testing'; |
| 2 | +import { |
| 3 | + ActivatedRouteSnapshot, |
| 4 | + RouterStateSnapshot, |
| 5 | +} from '@angular/router'; |
| 6 | +import { |
| 7 | + firstValueFrom, |
| 8 | + of, |
| 9 | +} from 'rxjs'; |
| 10 | +import { PAGE_NOT_FOUND_PATH } from 'src/app/app-routing-paths'; |
| 11 | + |
| 12 | +import { HardRedirectService } from '../services/hard-redirect.service'; |
| 13 | +import { AuthService } from './auth.service'; |
| 14 | +import { notAuthenticatedGuard } from './not-authenticated.guard'; |
| 15 | + |
| 16 | +describe('notAuthenticatedGuard', () => { |
| 17 | + let authService: jasmine.SpyObj<AuthService>; |
| 18 | + let hardRedirectService: jasmine.SpyObj<HardRedirectService>; |
| 19 | + const mockRoute = {} as ActivatedRouteSnapshot; |
| 20 | + const mockState = {} as RouterStateSnapshot; |
| 21 | + |
| 22 | + beforeEach(() => { |
| 23 | + const authSpy = jasmine.createSpyObj('AuthService', ['isAuthenticated']); |
| 24 | + const redirectSpy = jasmine.createSpyObj('HardRedirectService', ['redirect']); |
| 25 | + |
| 26 | + TestBed.configureTestingModule({ |
| 27 | + providers: [ |
| 28 | + { provide: AuthService, useValue: authSpy }, |
| 29 | + { provide: HardRedirectService, useValue: redirectSpy }, |
| 30 | + ], |
| 31 | + }); |
| 32 | + |
| 33 | + authService = TestBed.inject(AuthService) as jasmine.SpyObj<AuthService>; |
| 34 | + hardRedirectService = TestBed.inject(HardRedirectService) as jasmine.SpyObj<HardRedirectService>; |
| 35 | + }); |
| 36 | + |
| 37 | + it('should block access and redirect if user is logged in', async () => { |
| 38 | + authService.isAuthenticated.and.returnValue(of(true)); |
| 39 | + |
| 40 | + const result$ = TestBed.runInInjectionContext(() => |
| 41 | + notAuthenticatedGuard(mockRoute, mockState), |
| 42 | + ); |
| 43 | + |
| 44 | + const result = await firstValueFrom(result$ as any); |
| 45 | + expect(result).toBe(false); |
| 46 | + expect(hardRedirectService.redirect).toHaveBeenCalledWith(PAGE_NOT_FOUND_PATH); |
| 47 | + }); |
| 48 | + |
| 49 | + it('should allow access if user is not logged in', async () => { |
| 50 | + authService.isAuthenticated.and.returnValue(of(false)); |
| 51 | + |
| 52 | + const result$ = TestBed.runInInjectionContext(() => |
| 53 | + notAuthenticatedGuard(mockRoute, mockState), |
| 54 | + ); |
| 55 | + |
| 56 | + const result = await firstValueFrom(result$ as any); |
| 57 | + expect(result).toBe(true); |
| 58 | + expect(hardRedirectService.redirect).not.toHaveBeenCalled(); |
| 59 | + }); |
| 60 | +}); |
0 commit comments