How can I enable react-i18n translation file to be used in the unit tests done with react-testing-library and jest?
You should not mock the translation, instead render the component with translation library as Higher Order Component, for example;
import React from 'react';
import i18n from '../../../i18n' // your i18n config file
import { render } from '@testing-library/react';
import ComponentName from './ComponentName';
import { I18nextProvider } from 'react-i18next'
test('renders all documents in the list', () => {
const c = render(
<I18nextProvider i18n={i18n}> // actually give translation to your component
<ComponentName />
</I18nextProvider>
);
// example if you have a key called example
expect(c.getByText(i18n.getDataByLanguage('en').translation.example)).toBeDefined();
});
Instead of calling your translation texts with i18n.getDataByLanguage('en') , you can give the default translation of your project, if it is French call it by i18n.getDataByLanguage('fr').
Also change your component like this, instead of taking useTranslation hook from props, take it inside the component with hooks
ComponentName.jsx
import { useTranslation } from 'react-i18next'
const ComponentName = () => {
const { t } = useTranslation()
return(
<p>{t('example')}</p>
)}
export default ComponentName;
Eventually I got the mock working like this (in App.js):
jest.mock('react-i18next', () => ({
useTranslation: () => ({
t: key => key,
i18n: { changeLanguage: jest.fn() }
})
}));
In case somebody needs this.
Additionally inside components I was just using t={key=>key}
, which enabled queries like this: expect(c.getByText('json.field.in.translation')).toBeDefined();