angular - 我怎样才能有条件地允许导航到用户

标签 angular testing service jasmine karma-jasmine

所以这是我的问题,我想在我的代码中测试这个 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']);
  });

如何传递 Angular 色?

也许是一个好的解决方案:

  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
    });
  }));

最佳答案

要测试守卫,你必须做这样的事情:

{ path : "", component : ComponentName, canActivate : [GuardName]}

编辑

案例一:

export class AuthRoleGuardService implements CanActivate {
  test : number = 0 ;
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this.test != 0) {
      return true;
    }

    this.router.navigate('/access-denied');
    return false;
  }
}

对于这种情况,用户将停留在他所在的页面,因为我无法访问目标页面

案例 2:

export class AuthRoleGuardService implements CanActivate {
  test : number = 0 ;
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this.test == 0) {
      return true;
    }

    this.router.navigate('/access-denied');
    return false;
  }
}

对于这种情况,用户将转到目标页面,因为 test 的值等于“0”

关于angular - 我怎样才能有条件地允许导航到用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57216358/

相关文章:

android - JobIntentService 未正常启动

javascript - Angular 5 在 ngIf 空结果上显示 "No data found"

angular - 如何在 Angular 列表中保留滚动位置?

html - 以 Angular 评估表达式两次

xml - 如何解析 XML 代码并获取所需的属性和值

testing - 字母数字会包含 _ 和空格吗?

android服务在一个单独的线程中?

r - R 包的 tests/和 inst/tests/之间的区别

python - pytest fixture 和测试都依赖于另一个 fixture

windows - 创建一个服务作为自动运行