How do I mock react-i18next and i18n.js in jest? How do I mock react-i18next and i18n.js in jest? reactjs reactjs

How do I mock react-i18next and i18n.js in jest?


You don't need to mock the t function, only the translate one is required. For the second one, your usage of the parameters are confusing, also, you need to return a Component.

I was able to make it work on my project. Here are my mock file and my Jest configuration

Jest configuration

"moduleNameMapper": {    "react-i18next": "<rootDir>/__mocks__/reacti18nextMock.js"}

The source code to mock react-i18next

/* global jest */import React from 'react'const react_i18next = jest.genMockFromModule('react-i18next')const translate = () => Component => props => <Component t={() => ''} {...props} />react_i18next.translate = translatemodule.exports = react_i18next


I used Atemu's anwser in my jest tests, but ended up with the following one line in the mock:

module.exports = {t: key => key};

Also modified jest config as well since I import 't' from 'i18next':

"moduleNameMapper": {    "i18next": "<rootDir>/__mocks__/reacti18nextMock.js"}


In my case, using the useTranslation hook with TypeScript, it was as follows:

const reactI18Next: any = jest.createMockFromModule('react-i18next');reactI18Next.useTranslation = () => {  return {    t: (str: string) => str,    i18n: {      changeLanguage: () => new Promise(() => {}),    },  };};module.exports = reactI18Next;export default {};

The jest.config.ts:

const config: Config.InitialOptions = {  verbose: true,  moduleNameMapper: {    'react-i18next': '<rootDir>/__mocks__/react-i18next.ts',  },};