ERROR mocking getAllAccounts method with Jasmine and MsalService - Angular

Discussão em 'Angular' iniciado por EliasM, Novembro 4, 2024.

  1. EliasM

    EliasM Guest

    I am facing issues with test-coverage using jasmine, for that I am working with MsalService-Entra (Microsoft Authentication Library) and Angular 15, I am using a method to get All user accounts from a list that MsalService library provides us and the idea is to create a test-coverage for that, specificaly for this line:

    this.msalService.instance.getAllAccounts().length


    So I tried in many ways but still I am having problems mocking that getAllAccounts method from msaservice library, this is my code that I tried and I hope you could help me with that.

    login.ts

    checkAndSetActiveAccount() {
    if (this.msalService.instance && this.msalService.instance.getAllAccounts().length > 0) {
    const accounts = this.msalService.instance.getAllAccounts();


    This is my login.spec.ts

    let msalServiceMock: jasmine.SpyObj<MsalService>;

    beforeEach(waitForAsync(() => {
    msalServiceMock = jasmine.createSpyObj('MsalService', ['instance', 'getAllAccounts']);

    TestBed.resetTestingModule();
    TestBed.configureTestingModule({
    imports: [
    RouterTestingModule.withRoutes(
    [{path: 'home', component: HomeComponent}]
    ),
    ],
    providers: [
    {provide: MsalService, useValue: msalServiceMock}
    ],
    declarations: [LoginComponent]
    }).compileComponents();
    }));
    ...

    it('checkAndSetActiveAccount() check and validate Active Account', ()=> {

    let mockAccounts =[
    { homeAccountId: '', environment:'', tenantId:'', username:'', localAccountId:'' }
    ];

    //msalServiceMock = TestBed.inject(MsalService);
    //mockMsalService.instance.setActiveAccount(mockData[0]);
    //spyOn(msalServiceMock, 'instance').and.returnValue(mockAccounts);
    spyOn(msalServiceMock.instance, 'getAllAccounts').and.returnValue(mockAccounts);
    //spyOn(component.msalService.instance, 'getAllAccounts').and.returnValue(of(mockData));
    component.checkAndSetActiveAccount();


    Error on console:

    Firefox 132.0 (Mac OS 10.15) LoginComponent processCredentials() is processing username and password checkAndSetActiveAccount() check and validate Active Account FAILED
    Error: <spyOn> : getAllAccounts() method does not exist
    Usage: spyOn(<object>, <methodName>) in node_modules/karma-jasmine/node_modules/jasmine-core/lib/jasmine-core/jasmine.js (line 9619)
    <Jasmine>

    Firefox 132.0 (Mac OS 10.15) LoginComponent processCredentials() is processing username and password username and password are empty strings FAILED
    TypeError: this.msalService.instance.getAllAccounts is not a function in main.js (line 98918)

    Continue reading...

Compartilhe esta Página