How to properly mock i18next

Viewed 1658

Here is a simplified version of both my function and test. Although I mocked the useTranslation I get the following error:

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

   7 | i18n
   8 |   .use(Backend)
>  9 |   .use(initReactI18next)

How do I properly mock to get rid of this error?

import React from 'react'
import { useTranslation } from 'react-i18next'
import * as Constants from 'constants'
import MyComponent from 'components'

const Dashboard = () => {
  const { t } = useTranslation('dashboard')
  return (
     <div> Dashboard 
      <MyComponent name={t(Constants.MYCOMPONENT)}/>
    </div>
  )
}

export default Dashboard
jest.mock('react-i18next', () => ({
  useTranslation: () => ({ t: (key) => key })
}))
it('Render Dashboard without crash', () => {
  const div = document.createElement('div')
  ReactDOM.render(<Dashboard/>, div)

})
2 Answers

The only way I could get this to work for our setup was the following:

jest.mock("react-i18next", () => ({
    initReactI18next: { type: "3rdParty", init: jest.fn() },
    useTranslation: () => ({ t: (key: string) => key }),
    Trans: ({ children }: { children: React.ReactNode }) => children,
}));

With initReactI18next: { type: "3rdParty", init: jest.fn() },

Being the final piece of the puzzle, as referenced here

There is no need to mock i18next, this lib supports cimode which will always return the passed key.

In order to enable it, all you need to do is to pass cimode as lang in the config.

In your tests env setup change the language to cimode:

await i18next.changeLanguage('cimode');

// from now all calls to `t('MY_TARANSLATION_KEY')` 
// will return the key (in this case `MY_TARANSLATION_KEY`)
Related