在异步功能中使用ts-mockito引发错误

问题描述 投票:0回答:1

我正在尝试使用ts-mockito测试API端点。一切顺利,直到我开始异步...我的测试:

it('should throw an error if the address is not valid',()=>{
  const mockedGeolocationService: GoogleGeolocationService = mock(GoogleGeolocationService);
  when(mockedGeolocationService.getLocation(address)).thenThrow(new Error("the address provided is not valid"));
  const geolocationService: IGeolocationService = instance(mockedGeolocationService);

  const addressService: AddressService = new AddressService(geolocationService, new MongoAddressRepository());
  expect(() => addressService.storeAddress(address)).to.throw("the address provided is not valid");
});

服务:

public storeAddress = (address: Address): void => {
  const location = this.geolocationService.getLocation(address);
  address.setLocation(location);
  this.addressRepository.store(address);
}

至此,一切正常。但是,当我开始实施地理位置服务时,由于它会执行http请求,因此不得不将其声明为Promise。

public storeAddress = async (address: Address): Promise<void> => {
  const location = await this.geolocationService.getLocation(address);
  address.setLocation(location);
  this.addressRepository.store(address);
}

然后,我将无法捕获所有引发的错误,如果毕竟引发了...任何线索,我应该如何捕获或引发此错误?预先感谢。

javascript typescript mocha chai ts-mockito
1个回答
0
投票

我想出了解决错误的方法,为了让别人有帮助,我会留下答案。事实是,由于它是一个异步函数,因此无法捕获错误。必须手动处理它并比较错误(作为字符串),如下所示:

it('should throw an error if the address is not valid',(done)=>{
    const mockedGeolocationService: GoogleGeolocationService = mock(GoogleGeolocationService);
    when(mockedGeolocationService.getLocation(address)).thenThrow(new Error("the address provided is not valid"));
    const geolocationService: IGeolocationService = instance(mockedGeolocationService);

    const addressService: AddressService = new AddressService(geolocationService, new MongoAddressRepository());
    addressService.storeAddress(address).catch(error => {
        expect(error.toString()).to.be.equal(new Error("the address provided is not valid").toString());
        done();
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.