【发布时间】:2021-12-29 06:53:18
【问题描述】:
如何使用 canActivate 保护编写角度路由的单元测试?如果我在路线上使用 canActivate 防护,我会遇到错误。如果不是,则不会引发任何错误并通过测试。请帮我举个合适的例子,并解释一下。
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(`Navigate to 'home' takes you to /home`, fakeAsync(() => {
router.navigate(['/home']).then(() => {
expect(location.path()).toEqual('/home');
});
flush();
}));
测试结果
Testing Router › Navigate to 'home' takes you to /home
Uncaught (in promise): Error: expect(received).toEqual(expected) // deep equality
Expected: "/home"
Received: "/"
Error: expect(received).toEqual(expected) // deep equality
【问题讨论】:
标签: javascript angular typescript jestjs jasmine