简体   繁体   中英

throw an error using ts-mockito in async function

I am trying to test an API endpoint using ts-mockito. Things went well until I started going async... my test:

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");
});

the service:

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

up to this point, everything works fine. But when I started to implement the geolocation service, I had to declare it as a promise because it does an http request.

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

Then I cannot capture the error thrown anymore, if it is thrown after all... Any clue how I should capture or throw this error? Thanks in advance.

I figured out how to handle the errors, I leave the answer just in case it helps somebody. The thing is that as it is an ansync function, it does not capture the error. It has to be manually handled and compare the errors (as strings), something like this:

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM