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};
返回组件;
},
}));
请注意,如果直接从节点_模块导入,则导入路径应为模块名称;如果从项目内导入,则导入路径应为相对于测试文件的文件路径