问题描述
我构建了一个小型 Angular 应用程序,现在我正在编写单元测试。到目前为止一切顺利,但是当我尝试测试我的 authGuard 时,我遇到了一些问题。我正在使用 Spectator。 我在规范的提供者部分提供了 platformId,但我希望能够覆盖它,以便我可以测试值 'server' 和 'browser' 的场景 我的代码用于 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: 'server' }],schemas: [CUSTOM_ELEMENTS_SCHEMA],};
const createService = createServiceFactory(config);
// some other tests here ....
it('should should navigate to /auth if running on browser and not authenticated',() => {
config.providers = [AppRoutingModule,useValue: 'browser' }];
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);
spectator.service.canActivate(null,null);
expect(spyNavigate).toHaveBeenCalled();
});
});
现在当我运行这个覆盖配置不起作用。这是意料之中的,因为在更改配置对象之前已经传递了它。 但是如何实现我的目标呢? 我试过这个:
describe('AuthGuard',};
// some other tests here ....
it('should should navigate to /auth if running on browser and not authenticated',useValue: 'browser' }];
const createService = createServiceFactory(config);
spectator = createService();
const spyNavigate = spyOn(spectator.service['router'],null);
expect(spyNavigate).toHaveBeenCalled();
});
});
但是这给了我错误 Error: 'beforeEach' should only be used in 'describe' function
,我觉得很困惑,因为我没有在本规范中使用 beforeEach。
我觉得像 spectator 这样的工具应该有一个简单的方法来做到这一点,它不是那么奇特,对吧?
感谢任何帮助!
解决方法
您可以通过将参数传递给 createService()
来实现:
createService({
providers: [...]
});