【问题标题】:How to test async Call for Angular service如何测试 Angular 服务的异步调用
【发布时间】:2022-01-10 13:01:03
【问题描述】:

我有以下 Angular 服务方法

  updateStorage(): void {
    this.authServiceRef = this.authService.authRequest('storage', {}).subscribe((result) => {
      this.storage = this.buildStorage(result);
      this.storageUpdate.emit({ ...this.storage });
    });
  }

并且面临测试那段代码的困难

我的测试看起来像

  fit('Update Storage Status', inject([AuthService], fakeAsync((authService: AuthService) => {
    spyOn(authService, 'authRequest').and.returnValue(Observable.of(storageStatus_50GB_LowUsageTest));
    spyOn(storageService, 'buildStorage');
    spyOn(storageService.storageUpdate, 'emit');

    
    storageService.updateStorage();
    tick(1000);


    expect(authService.authRequest).toHaveBeenCalledOnceWith('files', 'storage', {});
    expect(storageService.buildStorageStatus).toHaveBeenCalledTimes(1);
    expect(storageService.storageStatusUpdate.emit).toHaveBeenCalledTimes(1);

    //  FAILS - storageService.storage is undefined
    expect(storageService.storage.size).toEqual(storageStatus_50GB_LowUsageTest.size)
    expect(storageService.storage.maximum).toEqual(storageStatus_50GB_LowUsageTest.maximum);
    expect(storageService.storage.usedPercentage).toEqual(0.4)
    expect(storageService.storage.storageUsedSafeRound).toEqual(4);

  })));

所有间谍调用都很好并且它们通过了,但是 storageService.storageundefined

如何测试订阅函数中的代码?

【问题讨论】:

标签: angular unit-testing testing jasmine jasmine-async


【解决方案1】:

buildStorage 方法上使用 spyOn 将用存根替换被调用的方法(这将返回 undefined)。在这种情况下,您需要使用 callThroughand.returnValue 以确保它返回您的值期待

【讨论】:

  • 谢谢,这就是问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多