Angular 10-Guard单元测试



我需要一个如何用一些逻辑测试Guards的建议,比如,因为我有点困惑,如何在Jasmine/Karma:中使用mock/spies

@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((做了很多尝试,但都没有成功。

软件版本:

  • 角度10.1.0
  • Jasmine Core 3.6.0
  • 因果报应5.2.1

当您进行单元测试时,模拟您想要单元测试时注入的所有服务是一件好事。服务应与所有其他组件分开进行测试。当您模拟服务时,您可以完全控制服务的方法返回的内容。

在您的TestBed的提供商中,您应该有:

providers: [
{
provide: CredentialService,
useValue: {
getAuthorities: () => /* here what you want the getAuthorities method to return (apparently a promise) */,
isGuestOrAdmin: () => /* true or false */
}
]

如果在测试中您需要更改useValue返回中定义的方法,您可以使用监视这些属性

spyOn(TestBed.get(CredentialService), 'isGuestOrAdmin').and.returnValue(false);

例如。

相关内容

  • 没有找到相关文章

最新更新