[英]How to validate catch block of a function in Jest?
I have a basic stringify function that looks like this ->我有一个基本的 stringify function,看起来像这样 ->
export const stringify = <T>(value: T) => {
try {
return JSON.stringify(value);
} catch(error){
return ''
}
}
I want to write a test that can cover the catch block of the function. I've tried adding such a test ->我想编写一个可以覆盖 function 的 catch 块的测试。我尝试添加这样的测试 ->
it('should be able to check for errors', async () => {
await expect(stringify('')).rejects.toThrow()
})
But this test keeps throwing errors about the function not being a promise. The function isn't going into the catch block at all.但是这个测试一直抛出关于 function 不是 promise 的错误。function 根本没有进入 catch 块。
The main function isn't a promise so I can't use the promise functions of jest.主要的 function 不是 promise 所以我不能使用 promise 的 jest 功能。
How do I test the catch block?如何测试 catch 块?
There is no need to use async/await
in this test.本次测试不需要使用
async/await
。 Also when there is an error you are returning ''
from catch
block, meaning your function will not throw anything.此外,当您从
catch
块返回''
时出现错误,这意味着您的 function 不会抛出任何东西。
Something like will work for your case类似的东西适合你的情况
it('should be able to check for errors', () => {
expect(stringify(<error value>)).toBe('')
})
Expect the function definition to Throw期望 function 定义为 Throw
const functionDef = () => {
throw new TypeError("Error Message");
};
test("Test description", () => {
expect(functionDef).toThrow(TypeError);
expect(functionDef).toThrow("Error Message");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.