简体   繁体   English

如何在 Jest 中验证 function 的 catch 块?

[英]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.

相关问题 如何使用笑话在catch块的if语句中测试函数? - How to test a function within an if statement in catch block using jest? 使用玩笑测试catch块 - testing the catch block using jest 如何从 Jest 中的 try/catch 块检查错误 - How I can check error from try/catch block in Jest 如何使用Jest Node.js测试catch块? - How can I test a catch block using jest nodejs? 如何 Jest spyOn 返回块中的函数 - How to Jest spyOn a function in a return block 如何在外部 try/catch 块上的异步回调 function 上捕获错误 - How to catch an error on a async callback function on outer try/catch block 开玩笑:卡在 [UnhandledPromiseRejection:此错误源于在没有 catch 块的情况下抛出异步 function 内部, - Jest: stuck on [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, 如何通过 jest mock 验证错误消息以在 catch 块内抛出错误 - How to verify error message through jest mock for throw error inside catch block 如何在 mocking API 调用时测试 jest 和 react 测试库中的 catch 块? - How to test catch block in jest and react testing library while mocking API calls? 如何重构此 function 以在 catch 块中获得正确的错误消息? - How to refactor this function to get the correct error message in the catch block?
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM