【发布时间】:2019-07-26 08:46:25
【问题描述】:
所以这是我的问题,我想在我的代码中测试这个canActivate 函数。
我的 AuthRoleGuardService.ts 文件:
export class AuthRoleGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authService.currentUserSubject.value;
if (Roles[currentUser.role] >= route.data.role) {
return true;
}
this.router.navigate(['/access-denied'], { queryParams: { redirect: state.url }, replaceUrl: true });
return false;
}
}
这是我迄今为止尝试过的:
it('should allow navigation if user has minimum role', () => {});
it('should not allow navigation if user does not have minimum role', () => {
const role = 'DISPLAY';
const routerMock = jasmine.createSpyObj('Router', ['navigate']);
expect(roleGuard.canActivate(undefined, ({ url: 'users' } as any) as RouterStateSnapshot)).toBe(false);
expect(routerMock.navigate).toHaveBeenCalledWith(['access-denied']);
});
如何传递角色?
也许是一个很好的解决方案:
it('should not allow navigation if user does not have minimum role', fakeAsync(() => {
user.role = 'DISPLAY';
const route = new ActivatedRouteSnapshot();
route.data = { role: Roles.SHIFTLEAD };
expect(roleGuard.canActivate(route, mockStateSnapshot)).toBe(false);
expect(mockRouter.navigate).toHaveBeenCalledWith(['/access-denied'], {
queryParams: { redirect: undefined },
replaceUrl: true
});
}));
【问题讨论】:
标签: angular testing service jasmine karma-jasmine