3

我将 i18n 添加到我的反应应用程序中使用react-i18next. 我有一个组件 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 函数?

4

1 回答 1

0

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

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

请注意,如果直接从 node_modules 导入,则导入路径应该是模块名称,如果从项目中导入,则应该是相对于测试文件的文件路径。

于 2019-03-26T13:59:46.973 回答