import { UserService } from './user.service'; import { Router } from '@angular/router'; import { TestBed, inject } from '@angular/core/testing'; import { AuthGuard } from './auth-guard.service'; describe('AuthGuard', () => { beforeEach(() => { const router = { navigate: jasmine.createSpy('navigate') }; const user = { auth: false, login: () => this.auth = true, logout: () => this.auth = false, loggedIn: () => this.auth }; TestBed.configureTestingModule({ providers: [ AuthGuard, { provide: UserService, useValue: user }, { provide: Router, useValue: router } ], }); }); it('should be able to activate when user is logged in, and prevent it otherwise', inject([AuthGuard, UserService, Router], (service: AuthGuard, user: UserService, router: Router) => { // user is not authenticated user.logout(); expect(user.loggedIn()).toBe(false); const canActivate = service.canActivate({}, {}); expect(canActivate).toBe(false); expect(router.navigate).toHaveBeenCalledTimes(1); expect(router.navigate).toHaveBeenCalledWith(['/auth/login']); })); it('should be able to activate when user is logged in, and prevent it otherwise', inject([AuthGuard, UserService, Router], (service: AuthGuard, user: UserService, router: Router) => { // user is authenticated user.login(null, null); expect(user.loggedIn()).toBe(true); const canActivate = service.canActivate({}, {}); expect(canActivate).toBe(true); expect(router.navigate).toHaveBeenCalledTimes(0); })); });