【问题标题】:React - unit testing HOC’s wrapped component - testing stateReact - 单元测试 HOC 的包装组件 - 测试状态
【发布时间】:2020-09-09 02:13:54
【问题描述】:

我想使用 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(&lt;MyComponent /&gt;).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 的情况下对其进行测试。我不得不承认我不喜欢这种方法,但它应该可以工作。
  • 这就是我想要避免的。无论如何,非常感谢!

标签: reactjs unit-testing testing enzyme higher-order-components


【解决方案1】:

兄弟你在测试 HOC 组件时使用了 dive() 查看enzyme's dive

wrapper.dive()

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 2019-07-04
    • 2017-11-19
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多