React / Enzyme:运行 Jest / Enzyme 测试时出现 Invariant Violation 错误
Posted
技术标签:
【中文标题】React / Enzyme:运行 Jest / Enzyme 测试时出现 Invariant Violation 错误【英文标题】:React / Enzyme: Invariant Violation error when running Jest / Enzyme test 【发布时间】:2019-02-06 01:57:33 【问题描述】:我在使用 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 />
会在这里未定义。
【问题讨论】:
【参考方案1】:您当前正在将包装组件导出为默认导出,但要在测试中使用未包装组件,您还需要将其导出为命名导出,即
export class DashboardComponent extends Component ...
export default connect(...)(DashboardComponent)
【讨论】:
就是这样。谢谢! 如果您没有传递组件渲染所需的道具,也可能导致此错误。 哇,我不敢相信我从来没有想过这个。干得好!【参考方案2】:错误:ReactShallowRenderer render():浅渲染仅适用于自定义组件,但提供的元素类型为 `object`。
- 通过更改导出行解决了类似的错误,来自
export const TestComponent = () => ...
到
导出默认 TestComponent = () => ...
【讨论】:
以上是关于React / Enzyme:运行 Jest / Enzyme 测试时出现 Invariant Violation 错误的主要内容,如果未能解决你的问题,请参考以下文章