繁体   English   中英

基于 Keycloak 角色的重定向导致 angular 应用程序中的单元测试错误

[英]Keycloak role based redirection causes unit test error in angular app

我有一个 angular 应用程序,它应该根据用户角色重定向到 /route1 还是 /route2。 问题是keycloak在登录后必须有一个重定向到的路由(在我的例子中是route1),这就是我解决路由问题的方法:

我在用户重定向到 /route1 时加载的组件的 ngOnInit 中有这个:

在此处输入图像描述

如果用户的角色是角色 2,所有这些都会将用户重定向到 /route2,否则什么也不会发生。

问题是当我尝试运行单元测试时 isUserInRole 会导致错误: 在此处输入图像描述

这是单元测试的样子:

在此处输入图像描述

问题是您正在为您的单元测试提供真正的KeycloakService并且这很难做到,因为keycloakService正在读取 hasResourceRole 的属性/方法,并且此属性/方法所在的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 },
  ],

执行上述操作应该有望使其发挥作用。

在此处阅读有关组件测试中的 mocking 服务的信息: https://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM