Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation.
app-routing.module.ts
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
test(`Navigating to 'home' should redirect you to /home`, fakeAsync(() => {
router.navigate(['/home']).then(() => {
expect(location.path()).toEqual('/home');
});
flush();
}));
Test Result
Testing Router › Navigating to 'home' should redirect you to /home
Uncaught (in promise): Error: expect(received).toEqual(expected) // deep equality
Expected: "/home"
Received: "/"
Error: expect(received).toEqual(expected) // deep equality