【问题标题】:How do I test HOCs with ReactJS, Enzyme and Jest?如何使用 ReactJS、Enzyme 和 Jest 测试 HOC?
【发布时间】:2018-11-04 16:08:32
【问题描述】:

我想测试该组件接收道具,以及单击按钮会增加值。

我知道如何在不使用 HOC 的情况下进行测试,但我不知道如何使用它进行测试。

例子:

// component
const Test = ({ value, increment }) => {
  return (
    <div>
      {value}
      <button onClick={increment}>Click</button>
    </div>
  );
}
Test.propTypes = {
  name: PropTypes.string.isRequired,
  increment: PropTypes.func.isRequired
}

// higher order component
const test = WrappedComponent => {
  return class extends Component {
    state = { value: 0 }

    increment = () => {
      this.setState({ value: this.state.value + 1 });
    }

    render() {
      return (
        <WrappedComponent 
          increment={this.increment} 
          value={this.state.value} />
      );
    }
  }
}

// test
// Error: failed the prop type name
it("renders without crashing", () => {
  const Container = test(Test);
  shallow(<Container />);
});

【问题讨论】:

    标签: reactjs jestjs enzyme higher-order-components


    【解决方案1】:

    你可以“转发”道具:

    const test = WrappedComponent => {
      return class extends Component {
        state = { value: 0 }
    
        increment = () => {
          this.setState({ value: this.state.value + 1 });
        }
    
        render() {
          return (
            <WrappedComponent 
              increment={this.increment} 
              value={this.state.value}
              {...this.props}
            />
          );
        }
      }
    }
    
    it("renders without crashing", () => {
      const Container = test(Test);
      shallow(<Container name="foo" />);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-21
      • 2017-04-13
      • 2018-11-09
      • 2018-09-08
      • 2017-11-26
      • 1970-01-01
      • 2019-05-01
      • 2017-11-10
      相关资源
      最近更新 更多