React--单元测试HOC的封装组件--测试状态。

问题描述 投票:0回答:1

我想使用Enzyme.Simple测试来测试我的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.comc-hivetest-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);
  });
reactjs unit-testing testing enzyme higher-order-components
1个回答
0
投票

兄弟你有使用潜水(),而测试HOC组件看成 酶的潜水

wrapper.dive()
© www.soinside.com 2019 - 2024. All rights reserved.