我有一个异步函数,如果它的参数是假的,则会抛出错误:
public async publish(type: string, payload: any): Promise<any> {
if (!type) {
throw new Error(`Type is invalid: ${type}`);
}
// ... do things ...
return useNetworkLayerToPublish(type, payload);
}
然后返回带有网络连接结果的Promise。
必须为async
,因为其逻辑使用await
。
在它是异步函数之前,测试用例非常简单:
it("should throw an error is type is undefined", () => {
const test = () => metrics.publish(undefined, []);
expect(test).to.throw("Type is invalid: undefined");
});
但现在我想知道如何保留这种格式,我尝试过这样的事情:
// 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");
});
但它们都没有像我期望的那样工作。这甚至是可能的还是在.catch()
内预期错误的唯一方法?