I'm new with the implementation of keycloak-angular package, everything is working but I need to write some test, and it's not clear how to approach this topic, I did some research and I wrote some tests but I need to call the keycloak method or I need to fake it or mock it, but I need to know what the keycloak is returning me when the user is successfuly loggedin, so I can test the login flow.
component:
isLoggedIn = false;
constructor(private readonly keycloak: KeycloakService) {}
public async ngOnInit() {
this.isLoggedIn = await this.keycloak.isLoggedIn();
if (!this.isLoggedIn) {
this.keycloak.login();
}
}
logout() {
this.keycloak.logout();
}
and here are the tests:
fdescribe('MainPageComponent', () => {
let component: MainPageComponent;
let fixture: ComponentFixture<MainPageComponent>;
let keycloakService: jasmine.SpyObj<KeycloakService>;
beforeEach(async () => {
const spy = jasmine.createSpyObj('KeycloakService', [
'login',
'isLoggedIn',
]);
await TestBed.configureTestingModule({
declarations: [MainPageComponent],
imports: [BrowserAnimationsModule],
providers: [{ provide: KeycloakService, useValue: spy }],
}).compileComponents();
fixture = TestBed.createComponent(MainPageComponent);
keycloakService = TestBed.inject(
KeycloakService
) as jasmine.SpyObj<KeycloakService>;
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create MainPageComponent', () => {
expect(component).toBeTruthy();
});
it('should called login when the user is not loggin', () => {
component.ngOnInit();
let loggedIdUser = component.isLoggedIn;
expect(keycloakService).toBeDefined();
expect(loggedIdUser).toBeFalsy();
expect(keycloakService.login).toHaveBeenCalled();
});
});
App Init:
function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
url: 'xxx',
realm: 'xxx',
clientId: 'xxx',
},
loadUserProfileAtStartUp: false,
initOptions: {
onLoad: 'check-sso',
checkLoginIframe: false,
},
});
}
if some can show me the way, because I can't find too much about this topic. :)