Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何测试包装在“包装”中的组件;withNamespaces";那些有;innerRef";?_Javascript_Reactjs_Jestjs_React I18next - Fatal编程技术网

Javascript 如何测试包装在“包装”中的组件;withNamespaces";那些有;innerRef";?

Javascript 如何测试包装在“包装”中的组件;withNamespaces";那些有;innerRef";?,javascript,reactjs,jestjs,react-i18next,Javascript,Reactjs,Jestjs,React I18next,我使用react-i18next将i18n添加到我的react应用程序中。 我有一个组件a,它使用对子组件B的引用,如下所示: export const withNamespaces = (ns, options) => (Component) => { if (options && options.innerRef) { // ***What can I do here?*** } Component.defaultProps

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

export const withNamespaces = (ns, options) => (Component) => {
    if (options && options.innerRef) {
        // ***What can I do here?***
    }
    Component.defaultProps = { ...Component.defaultProps, t: key => key };
    return Component;
}
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"
      />
    );
  }
}
class B extends Component {
  render() {
    return (
      <div>Some content...</div>
    );
  }
}

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

如何实现此测试?如何将测试中创建的实际引用传递给innerRef函数?

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

jest.mock('<import path to i18n>', () => ({
    withNamespaces: () => Component => {
        Component.defaultProps = { ...Component.defaultProps, t: key => key };
        return Component;
    },
}));
jest.mock(“”,()=>({
withNamespaces:()=>Component=>{
Component.defaultProps={…Component.defaultProps,t:key=>key};
返回组件;
},
}));
请注意,如果直接从节点_模块导入,则导入路径应为模块名称;如果从项目内导入,则导入路径应为相对于测试文件的文件路径