0

I have an angular app which should whether redirect to /route1 or to /route2 based on the user role. The thing is that keycloak must have a single route to redirect to after logging in (which in my case is route1) and this is how I have solved the routing issue:

I have this in ngOnInit of the component that gets loaded when the user is redirected to /route1:

enter image description here

All this does is redirect the user to /route2 if their role is role2, otherwise nothing happens.

The issue is that the isUserInRole causes an error when I try to run the unit test: enter image description here

This is what the unit test looks like:

enter image description here

1 Answers1

0

The problem is you're providing the real KeycloakService for your unit test and it is tough to do because keycloakService is reading a property/method of hasResourceRole and the object this property/method is on is undefined.

I would mock KeycloakService like so:

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 },
  ],

Doing the above should hopefully make it work.

Read about mocking services in component tests here: https://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services.

AliF50
  • 16,947
  • 1
  • 21
  • 37