【发布时间】:2020-09-10 07:28:34
【问题描述】:
我需要一个建议如何用一些逻辑来测试 Guards,因为我有点困惑,如何在 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();
});
}
}
这是服务:
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();
})
}
}
是否有可能模拟服务?我尝试了很多使用 TestBed.inject() 的方法,但没有成功。
软件版本:
- Angular 10.1.0,
- Jasmine Core 3.6.0,
- 业力 5.2.1
【问题讨论】:
-
你读过 Angular 的测试文档吗?它们涵盖了很多不同的情况,包括注入测试替身:angular.io/guide/testing。如果您有具体问题,请给minimal reproducible example 提供比“没有成功” 更好的问题描述。
-
是的,我读过,但问题是我有
canActivate方法主体的特定案例 -
然后给出该特定问题的 MRE。
标签: angular unit-testing testing jasmine karma-runner