I need an advice how to test Guards with some logic like, because I am a little bit confused, how to use mocks/spies in Jasmine/Karma:
@Injectable({
providedIn: 'root'
})
export class RegistrationGuardService implements CanActivate {
constructor(private credentials: CredentialsService,
private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.credentials.getAuthorities().then(() => {
if (!this.credentials.isGuestOrAdmin()) {
this.router.navigate(['/sign-in'], {state: {url: routerState.url}});
}
return this.credentials.isGuestOrAdmin();
});
}
}
and this is service:
export class CredentialsService {
authenticated: boolean = false;
authorities: UserRole[];
constructor(private router: Router,
private authenticationService: AuthenticationService,
private authorizationService: AuthorizationService,
private notificationService: NotificationService) {
this.getAuthorities().then();
}
public async getAuthorities() {
await this.authorizationService.getAuthorities()
.pipe(
map(authorities => authorities.map(element => UserRole.getUserRoleType(element)))
)
.toPromise()
.then(result => {
this.authorities = result;
this.authenticated = this.isNotAnonymous();
})
.catch(() => {
this.authorities = [UserRole.ANONYMOUS];
this.authenticated = this.isNotAnonymous();
})
}
}
Is it any possibility to mock services? I tried many things with using TestBed.inject() but without success.
Version of software:
- Angular 10.1.0,
- Jasmine Core 3.6.0,
- Karma 5.2.1
Aucun commentaire:
Enregistrer un commentaire