Angular MSAL Testing

53 Views Asked by At

Im using MSAL 3.0.9, MSAL Browser 3.6.0 and Angular 16.1.0

Mocking, init it, give it an empty variable

Hello everyone, I am facing a problem when testing my component. It uses the MSAL Services to log in the user. Unfortunately, I am not sure how to test this component. This is what my component looks like:

import { Component, OnInit } from "@angular/core";
import { MsalBroadcastService, MsalService } from "@azure/msal-angular";
import {
  EventMessage,
  EventType,
  InteractionStatus,
} from "@azure/msal-browser";
import { Subject, filter, takeUntil } from "rxjs";

export interface ProfileType {
  id?: string;
  givenName?: string;
  surname?: string;
  userPrincipalName?: string;
}

@Component({
  selector: "app-auth",
  templateUrl: "./auth.component.html",
  styleUrls: ["./auth.component.css"],
})
export class AuthComponent implements OnInit {
  loginDisplay: boolean = false;
  private readonly _destroying$ = new Subject<void>();

  constructor(
    private msalService: MsalService,
    private msalBroadcastService: MsalBroadcastService
  ) {}

  async ngOnInit(): Promise<any> {
    await this.msalService.instance.initialize();
    this.setLoginDisplay();
    this.msalService.instance.enableAccountStorageEvents();

    this.msalBroadcastService.msalSubject$
      .pipe(
        filter(
          (msg: EventMessage) =>
            msg.eventType === EventType.ACCOUNT_ADDED ||
            msg.eventType === EventType.ACCOUNT_REMOVED ||
            msg.eventType === EventType.LOGIN_SUCCESS
        ),
        takeUntil(this._destroying$)
      )
      .subscribe((result) => {
        this.checkAndSetActiveAccount();
        this.setLoginDisplay();
      });

    this.msalBroadcastService.inProgress$
      .pipe(
        filter(
          (status: InteractionStatus) => status === InteractionStatus.None
        )) .subscribe(() => {
        console.log("MSAL Done");
      });
  }

  setLoginDisplay() {
    this.loginDisplay = this.msalService.instance.getAllAccounts().length > 0;
  }

  checkAndSetActiveAccount() {
    let activeAccount = this.msalService.instance.getActiveAccount();

    if (
      !activeAccount &&
      this.msalService.instance.getAllAccounts().length > 0
    ) {
      let accounts = this.msalService.instance.getAllAccounts();
      this.msalService.instance.setActiveAccount(accounts[0]);
    }
  }

  login() {
      this.msalService.loginRedirect();
  }

  logout() {
    this.msalService.logoutRedirect();
  }

  _destroy() {
    this._destroying$.next(undefined);
    this._destroying$.complete();
  }
}

My Test looks like this, but i got an error, because this.msalService.instance is undefined:

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { AuthComponent } from './auth.component';
import { MockComponents, MockProviders } from 'ng-mocks';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { MatIcon } from '@angular/material/icon';

describe('AuthComponent', () => {
  let component: AuthComponent;
  let fixture: ComponentFixture<AuthComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AuthComponent],
      providers: [
        MockProviders(MsalBroadcastService, MsalService)
      ],
      imports: [
        MockComponents(MatIcon)
      ]
    });
    fixture = TestBed.createComponent(AuthComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
0

There are 0 best solutions below