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.
I tried importing my i18n module that initializes i18next and unit testing it using jest.
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;
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)
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?
Try this:
const reactI18nextModule = require("react-i18next");
instead of
import { initReactI18next } from "react-i18next";
read a bit more about require vs import for jest testing here:
Jest mocking default exports - require vs import
hope it helps :)