我正在进行一个测试,在测试中我正在调用一个 API,我希望该 API 会抛出异常。我想检查API调用是否抛出异常。如果是,则通过测试,如果不是,则测试失败。 这是我的测试:
it("expecting API to throw an error",async () =>{
const contractResponse = await axios.get("API endpoint");
})
我已经用
expect.fail()
和 expect(async ()=>{...}).to.throw()
进行了测试,但这两个都未通过测试。我想在API抛出异常时通过测试。我该怎么做?
由于
axios.get
显然是异步的,因此您需要同步 wait
调用来捕获所有异常,这就是技巧。因为我没有 axios.get
和 if
,所以我会嘲笑这些函数:
// mock some call to throw exception (or not)
const exceptionSource = async () => {
// comment out to see unexpected behavior:
throw new Error("exceptionSource throws an exception");
};
enter code here
// mock it:
const it = async (text, method) => {
console.log(text);
await method();
}
it("Expecting API to throw an error", async () => {
let expectedBehavior = false;
try {
await exceptionSource();
} catch (error) {
expectedBehavior = true;
}
console.log(`It behaves ${expectedBehavior
? "as expected"
: "incorrectly"}`);
// expect.fail() or something depending on expectedBehavior
})
您可以注释或取消注释
throw
来查看行为的两种变体,预期的(即抛出异常)和不正确的(即不抛出异常)。然后,根据 expectedBehavior
值,决定如何结束测试。
请记住,这只是想法的演示,您可能想从根本上改变它。请在实际测试中尝试类似的方法。