我的React应用程序中有一个ErrorHandler组件,我将其包裹在其他组件中以捕获错误。 ErrorHandler是一个Connected组件。它调用redux操作来记录捕获的错误。我正在尝试编写单元测试,但遇到了麻烦。这是我的ErrorHandler.test.js文件:
function ProblemChild() {
throw new Error('Error thrown from problem child1');
}
const initialState = {
errorText: "test error",
errorOccurred: true
};
const mockStore = configureMockStore();
let store, container, shallowContainer
beforeEach(() => {
store = mockStore(initialState);
const actions = {
setTrainingMode: jest.fn(),
setIsAVA: jest.fn()
}
container = mount(<Provider store={store}><ConnectedErrorHandler {...initialState} actions={actions} /><ProblemChild /></Provider>);
})
describe('<ErrorHandler />', () => {
it('renders an error', () => {
//const wrapper = mount(<ErrorHandler><ProblemChild /></ErrorHandler>);
console.log(container.debug());
expect(() => { container.html(); }).toThrowError('Error thrown from problem child');
expect(container.state().errorOccurred).to.equal(true);
});
});
我的ErrorHandler非常简单:
constructor(props) {
super(props)
this.state = {
errorOccurred: false
}
}
componentDidCatch(error, info) {
this.setState({ errorOccurred: true });
let errorObject = { "message": error, "description": info };
this.props.actions.logError(errorObject);
}
render() {
return this.state.errorOccurred ? <div className={styles.mapMessageContainer}><div className={styles.mapMessageText}>{this.props.errorText}</div></div> : this.props.children
}
按如下所示运行测试会返回错误:
不变违规:React.Children。仅预期接收单个React元素子级。
我认为ProblemChild元素引起了错误。