1

I have i18next-http-backend configured in my react app as follows:

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

i18n
    .use(Backend)
    .use(detector)
    .use(initReactI18next)
    .init({
        backend: {
            loadPath: `${process.env.PUBLIC_URL || ''}/locales/{{lng}}/{{ns}}.json`,
            addPath: null
        },
        fallbackLng: 'en',
        saveMissing: true,
        interpolation: {
            escapeValue: false // not needed for react as it escapes by default
        }
    })
export default i18n

In my test fixture, I want to mock the i18n aspect. For this I use the following boilerplate:

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: () => {}
    }
}))

The test also uses msw for mocking http endpoints, which indicates that my test still wants to talk to the http backend of i18next:

console.warn
      [MSW] Warning: captured a request without a matching request handler:
      
        • GET http://localhost/locales/en/translation.json

How can I mock i18next correctly, to prevent it from trying to talk to the http backend?

Hermann.Gruber
  • 1,257
  • 1
  • 12
  • 37
  • you may need to mock the fetch api – adrai Feb 02 '23 at 12:43
  • 1
    Have you tried also mocking `Backend` e.g. `jest.mock('i18next-http-backend')` – Ben Smith Feb 21 '23 at 14:13
  • 1
    @BenSmith thanks, this is the solution to my problem! Not very difficult once you know it :-) I found that out as well, but didn't get around to write the answer yet. If you want to convert your comment into an answer, I will gladly accept it. – Hermann.Gruber Feb 21 '23 at 16:04
  • 1
    Thats great news @Hermann.Gruber. Yes, solutions are always easy once you know the answer :) – Ben Smith Feb 21 '23 at 16:06

1 Answers1

1

You can get around this issue by mocking Backend from 'i18next-http-backend' e.g.

jest.mock('i18next-http-backend')

This will stop the HTTP request from being made.

Ben Smith
  • 19,589
  • 6
  • 65
  • 93