Search code examples
reactjsjestjsreact-testing-libraryreact-i18next

how can i ise i18n in unit test from react testing library


I'm trying to get translations from i18n files in my unit testing, I've seen other answers but they work with just one i18n file, My problem is that, I have 2 files and the folder structure is like this,

  • i18n/en/translation.json
  • i18n/es/translation.json

and translation.json file is written like this {... "info":"information", "name":"Name", ...} doesn't have an export default.

and here is my test file,

import React from 'react'
import '@testing-library/jest-dom'
import {render} from '@testing-library/react'
import AddUsers from '../../components/AddUsers'

test('Render OK',()=>{
    
    const menuLinkUp =false

    const component =render(
            <AddUsers/>
        
    )
    component.getByText(" how can i call my i18n?")
})

I'm using react testing library and jest for doing this.


Solution

  • There is a section in the documentation: https://react.i18next.com/misc/testing.

    I would probably mock the react-i18next module, as it requires the least amount of changes.

    jest.mock('react-i18next', () => ({
      // this mock makes sure any components using the translate HoC receive the t function as a prop
      withTranslation: () => Component => {
        Component.defaultProps = { ...Component.defaultProps, t: () => "" };
        return Component;
      },
    }));
    

    (If you actually want to "inject" the translations: https://react.i18next.com/misc/testing#example-test-using-this-configuration)