【问题标题】:How to test React HOC function that is not passed into the wrapped component?如何测试未传递到包装组件中的 React HOC 函数?
【发布时间】:2021-05-10 06:04:57
【问题描述】:

我有一个这样的 HOC,我想测试 getStuff2 函数:

function withHoc(aComponent) {
  class hocClass extends React.Component {

    getStuff1 = () => {

    }

    getStuff2 = () => {

    }

    render() {
      return <aComponent {...this.props} getStuff1={this.getStuff1} />;
    }
}
}

我正在这样测试它:

class MockApp extends React.PureComponent {
  render() {
    return <p>Hello from your Mock App</p>;
  }
}

const MockWithHOC = withHoc(MockApp);

const wrapper = shallow(<MockWithHOC />);

it('Test getStuff2', () => {
    const result = wrapper.getStuff2();
});

但是当我运行它时,它显示getStuff2 未找到。当我打印出包装器时,我只看到我在渲染时传入的getStuff1

<MockApp getStuff1={[Function]} />

我不想将getStuff2 传递到包装的组件中,因为那里不需要它。它只需要作为 getStuff1 的辅助方法,那么有没有办法在不将其传递到包装组件的情况下访问该方法?

【问题讨论】:

标签: javascript reactjs react-hoc


【解决方案1】:

(我假设你使用的是enzyme,因为你使用的是shallow()

您可以使用wrapper.instance():

const result = wrapper.instance().getStuff2();

ShallowWrapper.instance()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 2020-08-09
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多