1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Unit testing CanActivateFn in Angular 18

Discussão em 'Angular' iniciado por vijred, Outubro 8, 2024.

  1. vijred

    vijred Guest

    In Angular 18 how can I write a unit test case for something that implements CanActivateFn like this?

    export const AuthorizedUserClaimGuard: CanActivateFn = (route, state) => {
    const auth = inject(AuthenticationService);
    const config = inject(ConfigurationService);

    if (!auth.authenticated) {
    auth.setState({
    route: state.url,
    });
    auth.logout();
    // tslint:disable-next-line: no-console
    console.info('User is not authenticated, redirecting to the login page.');
    }

    const userClaims = config.authorizedClaims;

    for (const userClaim of userClaims) {
    if (auth.hasPermission(userClaim)) {
    return true;
    }
    }
    return false;
    };


    I've tried the following code but it doesn't work because AuthorizedUserClaimGuard is not a class. Is there a way to make it work like this?

    describe('AuthorizedUserClaimGuard', () => {
    let guard: AuthorizedUserClaimGuard;
    let authentication: AuthenticationService;
    let configuration: ConfigurationService;

    beforeEach(async(() => {
    TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [
    {
    provide: AuthenticationService,
    useClass: MockAuthenticationService,
    },
    ],
    }).compileComponents();
    }));

    beforeEach(() => {
    authentication = TestBed.get(AuthenticationService);
    configuration = TestBed.get(ConfigurationService);
    configuration.setConfiguration(MOCK_CONFIGURATION);
    guard = new AuthorizedUserClaimGuard(authentication, configuration);
    });

    it('should return true for a logged in user', () => {
    const route = createMockRoute();
    const state = createMockRouteState();
    expect(guard.canActivate(route, state)).toBeTruthy();
    });
    }

    Continue reading...

Compartilhe esta Página