0

I have an async function that throws an error if its argument is falsy:

public async publish(type: string, payload: any): Promise<any> {
  if (!type) {
    throw new Error(`Type is invalid: ${type}`);
  }

  // ... do things ...

  return useNetworkLayerToPublish(type, payload);
}

Then returns a Promise with the network connection results.

It has to be async because its logic uses await.

Before it was an async function the test case was rather simple:

it("should throw an error is type is undefined", () => {
  const test = () => metrics.publish(undefined, []);

  expect(test).to.throw("Type is invalid: undefined");
});

But now I wonder how could I keep this format, I've tried things like:

// awaiting inside expect
it("should throw an error is type is undefined", async () => {
  const test = () => metricsService.publish(undefined, []);

  expect(await test).to.throw("Type is invalid: undefined");
});


// awaiting inside test
it("should throw an error is type is undefined", async () => {
  const test = async () => await metricsService.publish(undefined, []);

  expect(await test).to.throw("Type is invalid: undefined");
});


// awaiting everywhere
it("should throw an error is type is undefined", async () => {
  const test = async () => await metricsService.publish(undefined, []);

  expect(await test).to.throw("Type is invalid: undefined");
});


// passing the Promise directly
it("should throw an error is type is undefined", () => {
  const test = metricsService.publish(undefined, []);

  expect(test).to.throw("Type is invalid: undefined");
});

But none of them work as I expect. Is this even possible or is it the only way to expect the error inside .catch()?

josemigallas
  • 3,761
  • 1
  • 29
  • 68
  • Related: https://stackoverflow.com/questions/48824513/how-to-test-promise-returning-functions – T.J. Crowder Apr 27 '18 at 15:41
  • Please do be sure to [search thoroughly](/search?q=%5Bmocha%5D+test+promise+function) before posting. :-) More on searching [here](/help/searching). Happy coding! – T.J. Crowder Apr 27 '18 at 15:43

0 Answers0