Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly mock i18next

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)

})
like image 997
Martina Carter Avatar asked Oct 25 '25 02:10

Martina Carter


1 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

like image 146
Andrew Birks Avatar answered Oct 27 '25 16:10

Andrew Birks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!