Typescript 如何修复`TypeError:无法读取属性';类型';在测试i18next时使用Jest时的“未定义”
我有一个react项目,包括i18next=15.0.4和react-i18next=10.2.0依赖项。我已经创建了一个模块,用于使用react-i18next初始化i18next,我正在尝试使用Jest对这段代码进行单元测试 我尝试导入初始化i18next的i18n模块,并使用jest对其进行单元测试 这是我的i18n.ts模块Typescript 如何修复`TypeError:无法读取属性';类型';在测试i18next时使用Jest时的“未定义”,typescript,jestjs,i18next,react-i18next,Typescript,Jestjs,I18next,React I18next,我有一个react项目,包括i18next=15.0.4和react-i18next=10.2.0依赖项。我已经创建了一个模块,用于使用react-i18next初始化i18next,我正在尝试使用Jest对这段代码进行单元测试 我尝试导入初始化i18next的i18n模块,并使用jest对其进行单元测试 这是我的i18n.ts模块 import i18next from "i18next"; import { initReactI18next } from "react-i18next";
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
const config = {
resources: {
en: {
static: {},
},
},
fallbackLng: "en",
defaultNS: "static",
ns: "static",
interpolation: {
prefix: "[",
suffix: "]",
},
};
i18next.use(initReactI18next).init(config);
export default i18next;
我试图从我的测试代码中调用它,如下所示(i18n.test.ts):
我希望这个测试能够通过,但是我得到了以下错误:
TypeError: Cannot read property 'type' of undefined
at I18n.use (node_modules/i18next/dist/commonjs/i18next.js:257:18)
它基本上指出了i18next.js中的这段代码
value: function use(module) {
if (module.type === 'backend') {
this.modules.backend = module;
}
如何解决此问题?功能失败:
function use(module) {
if (module.type === 'backend') { // cannot read `type` of `undefined`
结论:模块
是未定义的
。它来自:
i18next.use(initReactI18next)
import { initReactI18next } from "react-i18next";
结论:
initReactI18next
未定义。它来自:
i18next.use(initReactI18next)
import { initReactI18next } from "react-i18next";
结论:
initReactI18next
不是从react-i18next
导出的,请尝试以下操作:
const reactI18nextModule=require(“react-i18next”)代码>
而不是
从“react-i18next”导入{initReactI18next}代码>
请在此处阅读更多有关jest测试的require vs import的信息:
希望它有帮助:)也许您从=V10
进行了更新。因为reactI18nextModule
在>=V10
中不再可用。尝试改用initReactI18next
有关更多详细信息,请转至,您很可能遵循了本指南:
它说你应该使用这个模拟:
jest.mock('react-i18next', () => ({
// this mock makes sure any components using the translate HoC receive the t function as a prop
withTranslation: () => Component => {
Component.defaultProps = { ...Component.defaultProps, t: () => "" };
return Component;
},
}));
但当您执行此操作时,您在此处尝试使用的initReactI18next
:
import { initReactI18next } from "react-i18next";
i18next.use(initReactI18next).init(config);
文档破坏了您:(
您需要的是删除存根或在存根模块中提供initReactI18next
键
我已经在这里通知了作者:您需要模拟initReactI18next
。请尝试以下操作:
jest.mock('react-i18next', () => {
const useMock = [k => k, {}];
useMock.t = k => k;
return {
useTranslation: () => useMock,
initReactI18next: () => {}
};
});
我怎样才能导出UseTransformation with require?我不明白这个问题:)你问的是关于es5模块导出的问题<代码>模块.exports=foo代码>initReactI18next
从“react-i18next”导出