Skip to content

Instantly share code, notes, and snippets.

@ArnoldM
Last active June 24, 2024 14:20
Show Gist options
  • Save ArnoldM/712de6d912a20cdeceb0bb52196bfa76 to your computer and use it in GitHub Desktop.
Save ArnoldM/712de6d912a20cdeceb0bb52196bfa76 to your computer and use it in GitHub Desktop.
Angular 18+ Guard testing
export const loggedInGuard: CanActivateFn = () => {
const jwtService = inject(JwtService);
return !!jwtService.getToken();
};
describe('loggedInGuard', () => {
it('should return true', waitForAsync(async () => {
TestBed.configureTestingModule({
providers: [
{
provide: JwtService,
useValue: { getToken: () => true },
},
{
provide: ActivatedRouteSnapshot,
useValue: {},
},
{
provide: RouterStateSnapshot,
useValue: {},
},
],
});
TestBed.runInInjectionContext(() => {
const route = inject(ActivatedRouteSnapshot);
const state = inject(RouterStateSnapshot);
// loggedInGuard function must be called from an injection context
const result = loggedInGuard(route, state);
expect(result).toBeTruthy();
});
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment