【问题标题】:Test failed when I mock throwError()当我模拟 throwError() 时测试失败
【发布时间】:2019-10-10 18:45:36
【问题描述】:

我试图测试一个方法的“错误案例”,但我认为如果我模拟一个方法,这个模拟会影响我所有的其他测试。

所以我尝试将我的方法的成功案例和错误案例分成2个描述。

当我启动测试覆盖时,错误案例被覆盖,但控制台中的测试失败......

https://image.noelshack.com/fichiers/2019/21/5/1558683399-test1.png

控制台消息:

https://image.noelshack.com/fichiers/2019/21/5/1558683502-test2.png

这是方法:

getAgreementSelector() {
this.isLoading = true;

this.frameworkAgreements$ = this.entityManager.getEntity(AgreementSelectorEntity, {})
  .pipe(
    take(1),
    map((dataEntity: any) => dataEntity.value),
    filter((data: Array<IFrameworkAgreement>) => !!data && data.length > 0));

this.frameworkAgreements$.subscribe((data: Array<IFrameworkAgreement>) => {
  this.isLoading = false;
  this.agreementValue = data;
  this.error = false;
  const sessionStorageFAId = sessionStorage.getItem('selectedAgreementId');
  if (sessionStorageFAId) {
    this.onCustomerSelected(sessionStorageFAId);
  } else {
    this.onCustomerSelected(this.agreementValue[0].id.toString());
  }
  for (let j = 0; j < this.agreementValue.length; j++) {
    if (this.agreementValue[j].id.toString() === sessionStorageFAId) {
      this.selectedFrameworkAgreement = this.agreementValue[j].id.toString();
    }
  }
}, (error: any) => {
  this.isLoading = false;
  if (error.status === 404 || error.status === 500 || error.status === 403) {
    this.hideErrorFlag = true;
    this.error = true;
  }
});

}

还有测试:

it('should set error variables if there is an error (status 404)', () => {

    // arrange
    UtilsTest.mockReturnValue(component['entityManager'], 'getEntity', throwError({ status: 404 }));

    // act
    component.getAgreements();

    component.agreements$.subscribe(() => {
      // assert
      expect(component.isLoadingDetails).toBeFalsy();
      expect(component.hideErrorFlag).toBeTruthy();
      expect(component.errorDetails).toBeTruthy();
    });

  }
);

谢谢!

【问题讨论】:

  • 不确定这是否是您的问题,但您应该在测试中使用fakeAsync
  • 我尝试了使用 try/catch 的异步方法,Antonis 下面的解决方案按预期工作! :) 谢谢你

标签: angular jestjs


【解决方案1】:

试一试:

it('should set error variables if there is an error (status 404)', async(() => {
  spyOn(component['entityManager'], 'getEntity').and.throwError({ status: 404 });

  try {
    await component.getAgreements();
  } catch (e) {
    expect(component.isLoadingDetails).toBeFalsy();
    expect(component.hideErrorFlag).toBeTruthy();
    expect(component.errorDetails).toBeTruthy();
  }
}));

【讨论】:

  • 不客气!我记得我有一个类似的案例。很可能您需要在async 模式下运行它。我会更新答案
猜你喜欢
  • 2021-10-16
  • 1970-01-01
  • 2018-02-07
  • 2021-12-25
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 2022-01-13
相关资源
最近更新 更多