尝试学习如何使用Jest / Typescript编写更好的测试。我想确保我可以测试错误。
我可以创建模拟方法,该方法将返回预期的数据数组,但是事实证明,测试错误很困难。
//program.ts
const listStacks = async (cf: CloudFormation): Promise<StackSummaries> => {
try {
const result = await cf.listStacks().promise();
if (result.StackSummaries) {
return result.StackSummaries;
}
return [];
} catch(e) {
console.log(e);
throw e;
}
这是下面的测试,请注意,我已尝试返回一个新的Error而不是throw,但这似乎也不起作用。
//program.test.js
it('handles errors gracefully', async () => {
expect.assertions(1);
const cfMock = {
listStacks: (): any => ({
promise: async () => {
throw new Error('ohh NOO!');
}
})
}
expect(() => listStacks(cfMock as CloudFormation)).toThrow();
笑话返回此:
expect(received).toThrow()
Received function did not throw .
最佳答案
listStacks
是async
函数。async
函数return the following:
Promise
,它将使用异步函数返回的值来解析,或者被异步函数内部抛出的未捕获异常拒绝。
在这种情况下,您将提供一个导致在async
函数中引发未捕获的异常的模拟,因此它将返回Promise
,该异常将被未捕获的异常拒绝。
要验证此行为,请将您的expect
行更改为以下内容:
await expect(listStacks(cfMock)).rejects.toThrow(); // SUCCESS
请注意,
toThrow
对于使用PR 4884的承诺是固定的,因此,如果您使用的是Jest
的旧版本(在22.0.0之前),则需要使用类似toEqual
的名称:await expect(listStacks(cfMock)).rejects.toEqual(expect.any(Error)); // SUCCESS