旁观者:单个测试(角通用)的覆盖提供程序



我构建了一个小的angular应用程序,现在我正在编写单元测试。到目前为止一切顺利,但当我试图测试我的authGuard时,我遇到了一些问题。我用的是旁观者。我在规范的providers部分提供了platformId,但我希望能够覆盖它,这样我就可以测试值为"服务器"one_answers"浏览器"的场景。我的代码是为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, { provide: PLATFORM_ID, 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', () => {
let spectator: SpectatorService<AuthGuard>;
const config = {
service: AuthGuard,
imports: [RouterTestingModule, HttpClientTestingModule],
providers: [AppRoutingModule, AuthService, { provide: PLATFORM_ID, useValue: 'server' }],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
};
// some other tests here ....
it('should should navigate to /auth if running on browser and not authenticated', () => {
config.providers = [AppRoutingModule, { provide: PLATFORM_ID, useValue: 'browser' }];
const createService = createServiceFactory(config);
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();
});
});

但这给了我错误Error: 'beforeEach' should only be used in 'describe' function,我发现困惑,因为我没有使用beforeEach在这个规范。

我觉得像旁观者这样的工具应该有一个简单的方法来做到这一点,它不是那么奇特,对吧?

任何帮助都是感激的!

您可以通过向createService()传递参数来实现:

createService({
providers: [...]
});

相关内容

  • 没有找到相关文章

最新更新