我有一个react项目,我已经包含了i18next = 15.0.4和react-i18next = 10.2.0依赖项。我创建了一个用react-i18next初始化i18next的模块,我正在尝试使用Jest对这段代码进行单元测试。
我尝试导入我的i18n模块初始化i18next并使用jest对其进行单元测试。
这是我的i18n.ts模块
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)中调用它:
import i18n from "./i18n";
describe("i18n", () => {
it("should work fine", () => {
const strings = {
key: "value",
};
i18n.addResourceBundle("en", "static", strings, true, true);
});
});
我希望这个测试通过,但我得到以下错误:
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;
}
我该如何解决这个问题?
试试这个:
const reactI18nextModule = require("react-i18next");
代替
import { initReactI18next } from "react-i18next";
在这里阅读更多有关需要vs导入以进行游戏测试的信息:
Jest mocking default exports - require vs import
希望能帮助到你 :)
失败的功能:
function use(module) {
if (module.type === 'backend') { // cannot read `type` of `undefined`
结论:module
是undefined
。它来自:
i18next.use(initReactI18next)
结论:initReactI18next
未定义。它来自:
import { initReactI18next } from "react-i18next";
结论:initReactI18next
不是从react-i18next
出口的东西
也许你已经从<= V9
更新到了> = V10
。因为reactI18nextModule
不再可用于> = V10
。尝试使用initReactI18next
代替。
有关更多详细信息,请访问https://react.i18next.com/latest/migrating-v9-to-v10