Unable to fetch for public folder locales in tests for React + i18next

Viewed 28

I've got a project which uses React, i18next for internationalization and jest for testing.

The issue

Whenever I try to run my tests, it seems the Backend plugin is doing some fetches to load the translations from the public/locales folder, which ends up in an ugly error in the console, which (the main part) says:

Error: Error: connect ECONNREFUSED 127.0.0.1:80 at Object.dispatchError

Furthermore, anywhere where I want to use any of the i18n functionalities tests fail. For example, i18n.exists(message) always returns false when running in tests.

My guess is that Backend is actually making a fetch call to public folder, and it fails because during tests the server is not listening and does not return anything from the public folder, so basically no translations are loaded.

The project configuration

// i18n.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: false,
    defaultNS: 'common',
    fallbackLng: ['es'],
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    ns: ['common', 'comments'],
    react: {
      useSuspense: false,
    },
  });

export default i18n;
// setupTests.js

import '@testing-library/jest-dom';

jest.mock('react-i18next', () => ({
  ...jest.requireActual('react-i18next'),
  useTranslation: () => ({
    ...jest.requireActual('react-i18next').useTranslation(),
    t: (key: string, interpolation: any) =>
      `T_${key}${
        interpolation
          ? `--${Object.keys(interpolation)
              ?.map((k) => `${k}:${interpolation[k]}`)
              .join('--')}`
          : ''
      }`,
  }),
}));

And the locales folder structure:

location of the locales folder inside the project

What I've tried

I've tried to remove the Backend plugin from the use clauses, and then this error disappears. However, translations do not load anymore in the live app, and the other i18n functionalities keep failing in the tests.

Also, I've tried to load manually the resources option, importing directly the json file as a resource, and then it seems to work both: errors disappear and i18n.exists works as expected. But I don't want to have to load all the json files for each namespace manually, since multiple languages are expected to be supported.

The question

How can I get Backend to be able to load the information from the public/locales folder, exactly the same as it does in the live app, so that i18n functionalities are working as expected?

Maybe should I mock the calls to public/locales folder? If so, how can I do so for all tests (I'm using fetch-mock-jest to mock fetch calls).

Thanks!

0 Answers
Related