首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在异步函数中使用ts-mockito抛出错误

在异步函数中使用ts-mockito抛出错误
EN

Stack Overflow用户
提问于 2019-12-09 07:28:17
回答 1查看 766关注 0票数 0

我正在尝试使用ts-mockito测试API端点。一切都很顺利直到我开始变得不同步。我的测试:

代码语言:javascript
复制
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");
});

服务:

代码语言:javascript
复制
public storeAddress = (address: Address): void => {
  const location = this.geolocationService.getLocation(address);
  address.setLocation(location);
  this.addressRepository.store(address);
}

到目前为止,一切都很好。但当我开始实现地理定位服务时,我不得不将其声明为promise,因为它执行http请求。

代码语言:javascript
复制
public storeAddress = async (address: Address): Promise<void> => {
  const location = await this.geolocationService.getLocation(address);
  address.setLocation(location);
  this.addressRepository.store(address);
}

那么我就不能再捕获抛出的错误了,如果它被抛出的话……我应该如何捕获或抛出这个错误,有什么线索吗?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-15 22:06:03

我想出了如何处理错误,我留下了答案,以防它对某人有帮助。问题是,由于它是一个ansync函数,所以它不会捕获错误。它必须手动处理并比较错误(作为字符串),如下所示:

代码语言:javascript
复制
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();
    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59240857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档