Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular 13 How to Mock ActivatedRouteSnapshot in Auth guard

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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']
    }
  } 
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading