Testing components using next-translate and i18n

Viewed 733

In our Next.js app we use vinissimus/next-translate package for translations. We set it up accordingly:

next.config.js:

const nextTranslate = require('next-translate')
module.exports = nextTranslate()

i18n.js config file:

{
  "locales": ["en"],
  "defaultLocale": "en",
  "pages": {
    "*": ["en"],
    "/": ["en"],
  }
}

Using it inside the component with useTranslation hook:

const App = () => {
  const { t, lang } = useTranslation();

  return (
    <Homepage>
          <span>{t(`${lang}:homepage.title.header`)}</span>
    </Homepage>

My question is how can I test it with jest with react-testing-library?

When I'm rendering my component in tests the translations do not work, only the key is returned. Also, I'd like to test it by getByText / findByText and passing:

{t(`${lang}:homepage.header`)}

How can I setup some kind of a wrapper or config for tests if I'm not using any i18nProvider in app but only this i18n.js config?

1 Answers

Here is an example wrapper:

// tests/wrapper.js
import { render } from '@testing-library/react'
import I18nProvider from 'next-translate/I18nProvider'

import commonEN from '../locales/en/common.json'

const Providers = ({ children }) => (
  <I18nProvider
    lang={'en'}
    namespaces={{
      common: commonEN
    }}
  >
    {children}
  </I18nProvider>
)

const customRender = (ui, options = {}) => render(ui, { wrapper: Providers, ...options })

export * from '@testing-library/react'

export { customRender as render }

A test would look like

// App.spec.js
import React from 'react'
import { render } from './tests/wrapper'
import App from './App'

jest.mock('next/router', () => ({
  useRouter() {
    return {
      asPath: '/'
    }
  }
}))

describe('App', () => {
  it('should render the app', async () => {
    const res = render(<App />)
  })
})
Related