Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix `TypeError: Cannot read property 'type' of undefined` when testing i18next with 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.

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?

like image 786
Jesus Avatar asked Jan 26 '23 12:01

Jesus


2 Answers

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 :)

like image 169
khpa Avatar answered Jan 29 '23 02:01

khpa


Most likely you followed this guide: https://react.i18next.com/misc/testing

It says you should use this 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;
  },
}));

But when you do this, there's no initReactI18next which you're trying yo use here:

import { initReactI18next } from "react-i18next";
i18next.use(initReactI18next).init(config);

The documentation sabotages you :(

What you need is to either remove stubbing or provide the initReactI18next key in your stub module.

I've notified the authors here: https://github.com/i18next/react-i18next-gitbook/pull/42

like image 28
Vanuan Avatar answered Jan 29 '23 02:01

Vanuan