[英]React - unit testing HOC’s wrapped component - testing state
我想使用酶测试我的 ReactJS 应用程序的 state。 简单测试 - 如果 state 会改变,模态显示 - 但我得到错误: ShallowWrapper::state() can only be called on class components
我的组件是 class 组件。
class Component extends PureComponent<ComponentProps> {
public state = {
hasError: false,
};
public render() {
const { hasError } = this.state;
return (
<>
<Modal
isOpen={hasError}
type="error"
/>
<button onClick={this.onBtnClik}
</>
);
}
private onBtnClik = () => this.setState({ hasError: true})
export default compose(
withRouter,
withStyles(styles),
connect(mapStateToProps, mapDispatchToProps),
)(Component) as any;
如您所见,我有很多 HOC,我无法测试我的 state。 我发现这篇文章: https://medium.com/c-hive/test-hocs-wrapped-component-with-jest-and-enzyme-e9155f80a217但是: wrapper = shallow(shallow(<MyComponent />).get(0));
仍然没有帮助我,所以我有点困惑,非常感谢任何建议。
我的测试:
it('should open Modal when error state is true', () => {
const wrapper = shallow(shallow(<Component />).get(0));
expect(wrapper.state('hasError')).toBe(true);
});
兄弟你在测试 HOC 组件时使用了潜水()查看酶的潜水
wrapper.dive()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.