网站搜索

typescript - 为什么这个服务中的 Angular 单元测试没有测试订阅的内容?


我正在使用 Angular 14。我正在尝试测试这个服务:

import { EnvironmentService } from './environment.service';
import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular';
import { InteractionStatus, RedirectRequest, EventMessage, EventType } from '@azure/msal-browser';
import { Subject, filter, takeUntil } from 'rxjs';
import { Inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0/me';

/**
 * Every method is disabled if the environment is for development
 */
@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  public isIframe: boolean = false;
  public loginDisplay: boolean = !this._environmentService.getEnvironment().production;
  public userLogged$: Subject<boolean> = new Subject<boolean>();
  private readonly _destroying$ = new Subject<void>();
  public profile: any = {
    displayName: "Dev Mode User"
  };

  constructor(
    @Inject(MSAL_GUARD_CONFIG) private _msalGuardConfig: MsalGuardConfiguration,
    private _msalService: MsalService,
    private _msalBroadcastService: MsalBroadcastService,
    private _httpClient: HttpClient,
    private _environmentService: EnvironmentService
  ) { }

  /**
   * Send thorugh observable the information if the user logged or not
   */
  setLoginDisplay() {
    console.log("setLoginDisplay called");
  }

  /**
   * Redirec to login display
   */
  loginRedirect(): void {
    if (this._environmentService.getEnvironment().production) {
      this._msalService.loginRedirect().subscribe(
        () => {
          this.setLoginDisplay();
        }
      );
    }
  }

}

在其他情况下,如果可观察对象是某个依赖项的属性,它是有效的,但在这里不知为何不起作用,因为我一直收到这个错误:Expected spy setLoginDisplay to have been called.。通过检查覆盖率,我注意到测试并没有考虑订阅的内容:

这是我尝试的对应 spec.ts 文件:

import { EnvironmentService } from './environment.service';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG } from '@azure/msal-angular';
import { MockService } from 'ng-mocks';
import { TestBed, tick } from '@angular/core/testing';

import { AuthenticationService } from './authentication.service';
import { AccountInfo, EventMessage, InteractionStatus } from '@azure/msal-browser';

const mockInstance: any = {
  enableAccountStorageEvents(): void { },
  getAllAccounts(): AccountInfo[] { return [] },
  getActiveAccount(): AccountInfo | null { return null },
  setActiveAccount(account: AccountInfo | null): void { }
}


describe('AuthenticationService', () => {
  let service: AuthenticationService;

  const mockMsalService = MockService(MsalService, {
    instance: mockInstance
  });
  const mockMsalBroadcastService = MockService(MsalBroadcastService, {
    msalSubject$: new Observable<EventMessage>(),
    inProgress$: new Observable<InteractionStatus>(),
  });
  const mockHttpClient = MockService(HttpClient);
  const mockEnvironmentService = MockService(EnvironmentService, {
    getEnvironment() { return { production: true } }
  });

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: EnvironmentService,
          useValue: mockEnvironmentService
        },
        {
          provide: MsalService,
          useValue: mockMsalService
        },
        {
          provide: MsalBroadcastService,
          useValue: mockMsalBroadcastService
        },
        {
          provide: HttpClient,
          useValue: mockHttpClient
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useValue: {}
        }
      ]
    });

    mockMsalBroadcastService.msalSubject$ = new Observable<EventMessage>();
    mockMsalBroadcastService.inProgress$ = new Observable<InteractionStatus>();
  });

  it('should call setLoginDisplay', fakeAsync(() => {
    service = TestBed.inject(AuthenticationService);
    const setLoginDisplaySpy = spyOn(service, "setLoginDisplay").and.callFake(() => { });
    const loginRedirectSpy = spyOn(mockMsalService, "loginRedirect").and.returnValue(new Observable<void>());
    service.loginRedirect();
    tick();
    expect(setLoginDisplaySpy).toHaveBeenCalled();

  }));


});

有人可以帮我,也许向我解释一下为什么会发生这种情况吗?提前谢谢你!^^

答案#1

我认为在你被监视的 mockMsalService 中的 new Observable() 并没有发出任何值。因此,即使你等待一个 tick,你的订阅也永远不会被执行。你可能想要改用 of(undefined) 或 of({}):

const loginRedirectSpy = spyOn(mockMsalService, "loginRedirect").and.returnValue(of(undefined));

由于 of 是同步工作的,你甚至可以从测试中移除 tick()。

答案#2

你正在假装打电话,看看这条线路:

const setLoginDisplaySpy = 
      spyOn(service, "setLoginDisplay").and.callFake(() => { });

它用于测试功能,而不是实际数据!