我在使用 Jest/Enzyme 编写的测试用例时遇到了一些问题。我有一个 React/Redux 组件,正在尝试编写一个基本测试,但出现以下错误:
Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was 'undefined'.
这是我的代码:
dashboardComponent.js
import '../stylesheets/dashboardComponent.css';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as dashboardActions from '../actions/dashboardActions';
class DashboardComponent extends Component {
constructor(props) {
super();
}
componentDidMount() {
this.props.actions.getDashboardContent();
}
render() {
return (
< SOME JSX HERE >
);
}
}
function mapStateToProps(state) {
return {
dashboardContent: state.dashboard.get('dashboardContent')
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(dashboardActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(DashboardComponent);
dashboardComponent.test.js
import React from 'react';
import { shallow } from 'enzyme';
import { DashboardComponent as Dashboard } from '../../components/dashboardComponent';
const wrapper = shallow(<Dashboard />);
describe('Dashboard', () => {
it('renders the Dashboard component', () => {
expect(wrapper).toMatchSnapshot();
});
});
我不知道为什么<Dashboard />
此处未定义。
最佳答案
您当前正在将包装的组件导出为默认导出,但要在测试中使用未包装的组件,您还需要将其导出为命名导出,即
export class DashboardComponent extends Component { ... }
export default connect(...)(DashboardComponent)
关于reactjs - react / enzyme : Invariant Violation error when running Jest/Enzyme test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52108597/