Home > Enterprise >  Angular 13 How to Mock ActivatedRouteSnapshot in Auth guard
Angular 13 How to Mock ActivatedRouteSnapshot in Auth guard

Time:07-22

Hello im working in Angular 13 project and im passing data to my authGuard and this is my code :

 @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(
        private route: Router,
        private userService: UserService) { }
    
      canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot,
      ): Observable<boolean> | Promise<boolean> | boolean {
    
//here im getting the roles i passed in the route module 
        let roles = route.data['roles'] as Array<string>;
    
        if (this.userService.hasRoles(roles)) {
          return true;
        }
    
        this.route.navigate(['']);
        return false;
    
      }
    }

and this is how im securing my component inside route module :

{
    path: '', component: MyComponent,
    canActivate: [AuthGuard],
    data: {
        roles: ['ROLE_ONE','ROLE_TWO']
    }
}

and this is my Unit Test :

fdescribe('AuthGuard Test', () => {
  let injector: TestBed;
  let userService: UserService;
  let guard: AuthGuard;
  let routeMock: any = { snapshot: {} };
  let routeStateMock: any = { snapshot: {}, url: '' };
  let routerMock = { navigate: jasmine.createSpy('navigate') }

  let activatedRouteSnapshotMock: ActivatedRouteSnapshot;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AuthGuard,
        { provide: Router, useValue: routerMock },
        UserService,
        HttpClientModule
      ],
      imports: [
        RouterTestingModule,
        HttpClientTestingModule
      ]
    });
    injector = getTestBed();
    userService = injector.inject(UserService);
    guard = injector.inject(AuthGuard);

  });

  it('#Should be created', () => {
    expect(guard).toBeTruthy();
  });

it('#Should return false and redirect to home Page', () => {
    expect(guard.canActivate(routeStateMock, routeStateMock)).toEqual(false);
  });

When i run my test im getting the following Error : TypeError: Cannot read properties of undefined (reading 'roles')

how i can mock the data property inside my ActivatedRouteSnapshot and set values to my roles propery ?

Thanks in advance.

CodePudding user response:

Since you're calling method guard.canActivate from test. You have mock routeMock as desired. Like it should contain data object too.

let routeMock: any = { 
  snapshot: {
    data: {
        roles: ['ROLE_ONE','ROLE_TWO']
    }
  } 
};
  • Related