使用 Jest 测试 i18next 时如何修复“TypeError:无法读取未定义的属性“类型" [英] How to fix `TypeError: Cannot read property 'type' of undefined` when testing i18next with Jest
问题描述
我有一个 react 项目,并且包含了 i18next = 15.0.4 和 react-i18next = 10.2.0 依赖项.我已经创建了一个用于使用 react-i18next 初始化 i18next 的模块,我正在尝试使用 Jest 对这段代码进行单元测试.
I have a react project and I have included i18next = 15.0.4 and react-i18next = 10.2.0 dependencies. I have created a module for initializing i18next with react-i18next and I'm trying to unit test this code using Jest.
我尝试导入初始化 i18next 的 i18n 模块并使用 jest 对其进行单元测试.
I tried importing my i18n module that initializes i18next and unit testing it using jest.
这是我的 i18n.ts 模块
Here is my module for 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):
And I'm trying to call it from my test code like this (i18n.test.ts):
import i18n from "./i18n";
describe("i18n", () => {
it("should work fine", () => {
const strings = {
key: "value",
};
i18n.addResourceBundle("en", "static", strings, true, true);
});
});
我希望这个测试通过,但我收到以下错误:
I would expect this test to pass, but instead I'm getting the following error:
TypeError: Cannot read property 'type' of undefined
at I18n.use (node_modules/i18next/dist/commonjs/i18next.js:257:18)
这基本上指出了 i18next.js 中的这段代码
Which basically points out to this code in i18next.js
value: function use(module) {
if (module.type === 'backend') {
this.modules.backend = module;
}
我该如何解决这个问题?
How can I fix this issue?
推荐答案
试试这个:
const reactI18nextModule = require("react-i18next");
代替
import { initReactI18next } from "react-i18next";
在这里阅读更多关于 require 和 import 以进行玩笑测试的信息:
read a bit more about require vs import for jest testing here:
希望有帮助:)
这篇关于使用 Jest 测试 i18next 时如何修复“TypeError:无法读取未定义的属性“类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!