简体   繁体   English

使用React,Jest,React-Testing-Library测试失败的案例

[英]Test failing cases with React, Jest, React-Testing-Library

I have a React component that throws an Error when programming is wrong. 我有一个React组件,当编程错误时会抛出一个错误。 For example, the component Component takes the required prop data , and I have: 例如,组件Component接受所需的prop data ,而我有:

if (!data) { throw new Error("data is not provided") }

written in my component to handle this error. 写在我的组件中以处理此错误。 Using jest my test says: 使用jest我的测试说:

test("throw invalid component error", () => {
    mockConsole();
    const { container } = render(<Component />);
    expect(container).toThrowError();
});

When I run my test Jest says that the test fails and then it points me to the line where I have my throw new Error(...) written. 当我运行测试时,Jest说测试失败,然后它指向我编写throw new Error(...) Is what I'm trying to do possible in jest? 我在开玩笑地想做些什么吗?

To assert a function to throw an error, you have to pass a function to the expect statement. 要断言一个function引发错误,您必须将一个function传递给Expect语句。 In your case: 在您的情况下:

test('...', () => {
  expect(() => {
    render(<Component />);
  }).toThrowError();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何在Jest和react-testing-library中使用react-hook - How to use react-hooks with Jest and react-testing-library Jest &amp; React &amp; Typescript &amp; React-Testing-Library 错误 - Jest & React & Typescript & React-Testing-Library error 使用 react-testing-library 和 jest 测试是否调用了 prop 函数 - Testing if a prop function was called using react-testing-library and jest 使用 Jest + react-testing-library 测试异步 `componentDidMount()` - Testing async `componentDidMount()` with Jest + react-testing-library Jest/react-testing-library:单击按钮未更新测试中的值 - Jest/react-testing-library: Clicking a button didn't update the value in test 使用 Jest 和 react-testing-library 测试具有大量输入字段的表单的正确方法是什么? - What is the proper way to test a form with a lot of input fields using Jest and react-testing-library? 编写测试以使用 jest 和 react-testing-library 检查本地 setState 调用 - Write test to check local setState call with jest and react-testing-library 使用 test 和 react-testing-library 测试反应组件 - Test a react component using test and react-testing-library Jest + react-testing-library:警告更新未包含在 act() 中 - Jest + react-testing-library: Warning update was not wrapped in act()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM