如何测试“ withNamespaces” HOC中包含“ innerRef”的组件?

时间:2019-01-07 15:38:17

标签: javascript reactjs jestjs react-i18next

我使用react-i18next将i18n添加到了我的react应用程序中。 我有一个组件A,它使用对子组件B的引用,如下所示:

A.jsx:

class A extends Component {
  constructor() {
    super(this.props);
    this.refToB = null;
  }

  render() {
    return (
      <B
        setBref={(ref) => this.refToB = ref}
        prop1="prop1"
        prop2="prop2"
      />
    );
  }
}

B.jsx:

class B extends Component {
  render() {
    return (
      <div>Some content...</div>
    );
  }
}

export default withNamespaces(null, {
  innerRef: (ref) => {
    ref.props.setBref(ref)
  }
})(B);

现在,我想测试组件A,因此我对withNamespaces进行了模拟,如下所示:

export const withNamespaces = (ns, options) => (Component) => {
    if (options && options.innerRef) {
        // ***What can I do here?***
    }
    Component.defaultProps = { ...Component.defaultProps, t: key => key };
    return Component;
}

如何为此进行测试?我该如何真正将测试中创建的实际引用传递给innerRef函数?

1 个答案:

答案 0 :(得分:0)

您可以使用jest.mock模拟i18n模块并提供自己的模拟实现:

jest.mock('<import path to i18n>', () => ({
    withNamespaces: () => Component => {
        Component.defaultProps = { ...Component.defaultProps, t: key => key };
        return Component;
    },
}));

请注意,如果直接从node_modules进行导入,则导入路径应为模块名称;如果从项目内部进行导入,则导入路径应为相对于测试文件的文件路径

相关问题