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