【发布时间】:2018-02-14 11:35:40
【问题描述】:
有没有办法在 Jest 中测试组件中的自定义错误,而不会在控制台中抛出 Uncaught 错误?
这里我有一个简单的按钮组件:
import React from 'react';
export default class Button extends React.Component {
render() {
if (!this.props.type) {
throw new Error('Button requires a type prop');
}
return (
<button className={`btn btn-${this.props.type}`}>Button</button>
);
}
}
在不提供 type 属性的情况下使用组件时,我希望抛出我的自定义错误。我还有以下 Jest 测试:
import React from 'react';
import ReactDOM from 'react-dom';
import Button from './button';
it('throws an error if the type prop is not defined', () => {
const buttonType = undefined;
const container = document.createElement('div');
expect(() => {
ReactDOM.render(<Button type={buttonType} />, container);
}).toThrow('Button requires a type prop');
});
单元测试通过,但是控制台产生类似于以下的错误:
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Uncaught [Error: Button requires a type prop]
The above error occurred in the <Button> component:
in Button (at button.spec.js:20)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/docs/error-boundaries.html to learn more about error boundaries.
通常在 Jasmine 中,.toThrow() 匹配器会自动捕获错误并且不会有日志记录。
我已经阅读了有关错误边界的信息,但这些似乎是在应用程序级别,而不是在组件级别。
我是否缺少更适合测试的方法?
编辑:使用以下版本:
- 反应:16.2.0
- 反应域:16.2.0
- 开玩笑:22.2.2
【问题讨论】:
-
任何解决方案对您有用吗?我都试过了。没有成功。