React 16+中的反应,酶,Redux单元测试连接的组件

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

我正在尝试升级以响应16+,并且我现有的单元测试失败。该应用程序运行良好,只有单元测试失败。

已连接组件:

const componentsWrapper = (Components, selectData) => {

    class BaseComponent extends Component {

        constructor(props) {
            super(props);
            this.state = {
                saveMode: false,
                updateMode: false
            };
            this.foo = () => { };
        }

        render() {
          return (
              <Components
                  {...this.props}
              />
          );
        }

    }
  }

    const mapDispatchToProps = dispatch => {
        return selectData.getDispatch(dispatch);
    };
    const mapStateToProps = state => {
        return selectData.getStore(state);
    };

    return connect(mapStateToProps, mapDispatchToProps)(BaseComponent);
};

export default componentsWrapper;

单元测试:

class MockListComponent extends Component {
  render() {
      return (<div>Fake List</div>);
  }
}
Components = componentsWrapper(MockListComponent, selectComponents);
wrapper = shallow(<Components store={store} />).dive();
instance = wrapper.instance()
// Here instance is null hence the rest will fail.
instance.foo = jest.fn();

instance为空,因为“连接”组件正常运行或无状态。 Source

注意:在React 16及更高版本中,instance()对于无状态功能组件返回null。

我不知道如何使实例不为null或重构代码。感谢您的帮助或提示。

这些是我要使用的库版本:[email protected]酶@ [email protected]

reactjs redux enzyme
1个回答
0
投票

我不确定您要测试的确切行为是什么,但是在许多情况下,除非您打算进行集成测试或功能测试,否则无需显式“测试”整个连接的组件。

[为解决您面临的问题,建议您导出子组件(注意export上的BaseComponent):

const componentsWrapper = (Components, selectData) => {

  export class BaseComponent extends Component {

   // ... rest of the logic

  }

}

然后,在您的测试文件中,我们使用酶的.find()find与选择器匹配的节点。在这种情况下,我们的选择器为BaseComponent

const wrapper = shallow(<Components store={store} />)
const wrapperInstance = wrapper.dive().find(BaseComponent).instance();

从那里,您可以访问BaseComponent的类实例,并且可以使用它来调用其方法或监视其方法。

© www.soinside.com 2019 - 2024. All rights reserved.