我有一个角度应用程序,应该是重定向到/route1还是基于用户角色的/route2。问题是,keycloak必须有一个重新定向到登录后(在我的例子中是route1)的路由,这就是我如何解决路由问题的方法:
在组件的ngOnInit中有这样的内容,当用户被重定向到/route1时会加载该组件:

如果用户的角色是/route2,则只需将其重定向到role2,否则什么都不会发生。
问题是,当我试图运行单元测试时,isUserInRole会导致一个错误:

这就是单元测试的样子:

发布于 2022-08-05 13:22:58
问题是您正在为单元测试提供真正的KeycloakService,这很难做到,因为keycloakService正在读取hasResourceRole的属性/方法,并且该属性/方法所使用的对象是未定义的。
我会像这样嘲笑KeycloakService:
let fixture: ComponentFixture<MyComponent>;
let mockKeyCloakService: jasmine.SpyObj<KeycloakService>:
beforeEach(async () => {
// The first string argument is optional and it is there for debugging purpose
// where there are errors. The second array of strings are public methods you
// would like to mock.
mockKeyCloakService = jasmine.SpyObj<KeycloakService>('KeycloakService', ['isUserInRole']);
....
providers: [
ConfirmationService,
// provide the mock for the real KeycloakService
{ provide: KeycloakService, useValue: mockKeycloakService },
],希望这样做能让它发挥作用。
在这里了解有关在组件测试中模拟服务的内容:https://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services。
https://stackoverflow.com/questions/73236934
复制相似问题