0
votes

I'm having some issues with testing i18next, we are using jest + enzyme in a react project + redux.

We implemented react-i18next like so in a lib/i18n file:

import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { reactI18nextModule } from 'react-i18next';
import moment from 'moment';
import 'moment/locale/nl';

i18n
  .on('languageChanged', (lng) => {
    moment.locale(lng);
  })
  .use(LanguageDetector)
  .use(reactI18nextModule)
  .init({
    fallbackLng: 'en',
    debug: true,

    react: {
      wait: true,
    },
  });

export default i18n;

we created a __mocks__ folder and used the provided example in (https://github.com/i18next/react-i18next) __mocks__/react-18next.js we are seeing that once we import i18n and try to manipulate its properties from a non-jsx file this mock is not called. Our use case is the following:

We have an action that requests all the translations and uses the i18n.addResourceBundle in the response to set all the translations.

in this action, we import the ../lib/i18n.js file created for the effect, but once we start testing our action we keep on getting the following errors

TypeError: _i18next.default.on is not a function

       6 |
       7 | i18n
    >  8 |   .on('languageChanged', (lng) => {
         |    ^
       9 |     moment.locale(lng);
      10 |   })
      11 |   .use(LanguageDetector)

      at Object.on (src/lib/i18n.js:8:4)
      at Object.<anonymous> (src/actions/translation.js:2:1)
      at Object.<anonymous> (src/actions/translation.test.js:2:1)

we detected that the __mocks__/react-i18next.js does not get called, but if we create a __mocks__/i18next.js file it will mock the imported i18n instance what makes sense since within the configuration file lib/i18n.js we are importing it import i18n from 'i18next'; but once again the provided mock file within your project does not seem to work.

We are considering the following scenarios and would like to ask for an opinion: - migrate our fetch action to i18next-xhr-backend and we would like to ask you if this would fix the issue? since we no longer are going to import the config file and therefore no need to mock it, but we would lose our redux action logging functionality since we are using redux store to keep track of the user actions. - mock the file correctly in order to maintain the current functionality and for this, we would like to ask if anyone already experienced the same behavior.

Occurs in react-i18next version "react-i18next": "^9.0.2",

1

1 Answers

0
votes

I have managed to overcome that issue, I believe.

Replace line 35 in the mock with:

var selectedLanguage = "en-gb";
useMock.i18n = {
    language: selectedLanguage,
    changeLanguage: (lng) => selectedLanguage = lng,
};