Error : You are passing an undefined module! Please check the object you are passing to i18next.use()

Viewed 1021

My unit tests are failing due to the above issue.

//String.ts
import * as i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import BrowserLanguageDetector from 'i18next-browser-languagedetector'
import Backend from 'i18next-http-backend'
import languageMap from '@katal/localization/webpack-loader!'

i18n
  .use(initReactI18next)
  .use(BrowserLanguageDetector)
  .use(Backend)
  .init({
    fallbackLng: 'en-US',
    load: 'currentOnly',
    detection: {
      order: ['sessionStorage', 'localStorage', 'querystring', 'navigator'],
      lookupQuerystring: 'locale',
      lookupLocalStorage: 'locale',
      lookupSessionStorage: 'locale',
      caches: [],
    },
    backend: {
      loadPath: (localeList: string[]) => languageMap[localeList[0]],
    },
    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: false,
    },
  })

The way I'm mocking this is :

const React = require('react')
const reactI18next = require('react-i18next')



module.exports = {
  ...reactI18next,
  // this mock makes sure any components using the translate HoC or useTranslation hook receive the t function as a prop
  useTranslation: (...args) => ({
    ...reactI18next.useTranslation(...args),
    ready: true,
    t: (tr) => tr,
  }),
}

I'm import this in my App.tsx like

import './utils/Strings'

Some of the other links I checked are these and these but none of them work. Any help is appreciated on the workaround

1 Answers

I've been struggling quite some time on this as well.. My testing was fine until i decided to use i18n.t() on something outside a component. Jest didn't like that

Based on this answer i got it working https://github.com/i18next/i18next/issues/1426#issuecomment-828656983

Here is a solution working for me:

// setupTests.ts
jest.mock("react-i18next", () => ({
  // this mock makes sure any components using the translate hook can use it without a warning being shown
  useTranslation: () => {
    return {
      t: (str: string) => str,
      i18n: {
        changeLanguage: () => new Promise(() => {}),
      },
    };
  },
  initReactI18next: {
    type: "3rdParty",
    init: jest.fn(),
  },
}));

EDIT: didn't see adrai comment, he mentionned it first, but for clarity sake i'll keep my answer that display all the file content

Related