vendredi 26 juillet 2019

How can I create a test about if the user has minimum permission then it allows navigation

So here is my problem, i would like to test this canActivate function in my code.

My AuthRoleGuardService.ts file:

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

These are my tryings:

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

How can I pass the role?

Aucun commentaire:

Enregistrer un commentaire