问题描述
我发布了 another question 关于为一个小型 Angular 应用程序对我的 authGuard 进行单元测试,但即使在同一个测试中,我也看到了另一个不相关的问题。所以这就是我提出这个问题的原因。
@Injectable({
providedIn: 'root',})
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,private router: Router,@Inject(PLATFORM_ID) private platformId: Object,) {}
canActivate(
_route: ActivatedRouteSnapshot,_state: RouterStateSnapshot,): boolean | UrlTree | Promise<boolean | UrlTree> | Observable<boolean | UrlTree> {
if (isPlatformServer(this.platformId)) {
console.log('server');
return true;
} else {
console.log('browser');
this.authService.autoLogin();
return this.authService.user.pipe(
take(1),map((user) => {
console.log('user',user);
if (!!user) {
return true;
}
console.log('navugate');
this.router.navigate(['/auth']);
return false;
}),);
}
}
}
和规范文件:
describe('AuthGuard',() => {
let spectator: spectatorService<AuthGuard>;
const config = {
service: AuthGuard,imports: [RouterTestingModule,HttpClientTestingModule],providers: [AppRoutingModule,AuthService,{ provide: PLATFORM_ID,useValue: 'browser' }],schemas: [CUSTOM_ELEMENTS_SCHEMA],};
const createService = createServiceFactory(config);
it('should should navigate to /auth if running on browser and not authenticated',() => {
spectator = createService();
// const spyNavigate = spyOn(spectator.service['router'],'navigate').and.callThrough();
const user = new User('bla@bla.com','id','token',new Date(10000));
spectator.service['authService'].user.next(user);
const result = spectator.service.canActivate(null,null);
// expect(spyNavigate).toHaveBeenCalled();
expect(result).toEqual(false);
});
});
有两个地方出错了:
- 当我取消注释 spyNavigate 行时,它告诉我它从未被调用过。
- 当我这样离开他们时,它告诉我:
Error: Expected AnonymousSubject({ _isScalar: false,observers: [ ],closed: false,isstopped: false,hasError: false,thrownError: null,destination: AnonymousSubject({ _isScalar: false,destination: BehaviorSubject({ _isScalar: false,_value: User({ email: 'email',id: 'localId',_token: 'idToken',_expirationDate: Date(Thu Mar 04 2021 21:28:27 GMT+0100 (Central European Standard Time)) }) }),source: BehaviorSubject({ _isScalar: false,operator: TakeOperator({ total: 1 }) }),source: AnonymousSubject({ _isScalar: false,hasError: false ... to equal false.
我觉得这与 authGuard 中订阅的异步行为有关。
我尝试在规范中使用 fakeAsync
,然后在断言之前使用 tick()
,但也无法使其正常工作。
感谢这里的任何帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)