reactjs - React - 单元测试 HOC 的包装组件 - 测试状态
问题描述
我想使用 Enzyme 测试我的 ReactJS 应用程序的状态。简单的测试——如果状态会改变,模式就会出现——但我得到错误:
ShallowWrapper::state() can only be called on class components
我的组件是类组件。
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,我无法测试我的状态。我发现这篇文章:
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()
推荐阅读
- angular - 可观察的取消订阅方法不可用
- ruby-on-rails - 在 Rails 6 上使用 Rspec 测试控制器问题
- plc - 为什么我在完成所有数学运算后会收到累加器扩展警告?
- ibm-midrange - IBM i/AS400 系统运行状况电子邮件
- excel - 尝试在 VBA 中获取 API 数据的自动化错误
- javascript - 即使应用程序在后台,我如何每小时调用一个函数 - Cordova
- r - 语句 rm(list=ls()) 不会删除全局环境中的函数
- r - 基于节点删除或隐藏 iGraph 中的特定边
- sql - 子串?我可以使用此命令消除名称前的一些单词吗
- python - 如何将列添加到包含熊猫中列值对应的组名称的DataFrame