我有一个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";
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;
}
如何解决此问题?
发布于 2019-06-24 08:59:55
试试这个:
const reactI18nextModule = require("react-i18next");
而不是
import { initReactI18next } from "react-i18next";
在这里阅读更多关于jest测试的require import的信息:
Jest mocking default exports - require vs import
希望它能有所帮助:)
发布于 2019-12-22 21:24:42
您很可能遵循了以下指南:https://react.i18next.com/misc/testing
它说你应该使用这个mock:
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
密钥。
我已经在这里通知了作者:https://github.com/i18next/react-i18next-gitbook/pull/42
发布于 2019-06-25 13:10:02
也许你从<=V9
更新到了>=V10
。因为>=V10
中不再提供reactI18nextModule
。请尝试使用initReactI18next
。
有关更多详细信息,请访问https://react.i18next.com/latest/migrating-v9-to-v10
https://stackoverflow.com/questions/55507684
复制相似问题