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()
?