next-i18next Jest Testing with useTranslation

Viewed 6573

Testing libs...always fun. I am using next-i18next within my NextJS project. We are using the useTranslation hook with namespaces.

When I run my test there is a warning:

console.warn react-i18next:: You will need to pass in an i18next instance by using initReactI18next

> 33 |   const { t } = useTranslation(['common', 'account']);
     |                 ^

I have tried the setup from the react-i18next test examples without success. I have tried this suggestion too.

as well as just trying to mock useTranslation without success.

Is there a more straightforward solution to avoid this warning? The test passes FWIW...

test('feature displays error', async () => {
    const { findByTestId, findByRole } = render(
      <I18nextProvider i18n={i18n}>
        <InviteCollectEmails onSubmit={jest.fn()} />
      </I18nextProvider>,
      {
        query: {
          orgId: 666,
        },
      }
    );

    const submitBtn = await findByRole('button', {
      name: 'account:organization.invite.copyLink',
    });

    fireEvent.click(submitBtn);

    await findByTestId('loader');

    const alert = await findByRole('alert');
    within(alert).getByText('failed attempt');
  });

Last, is there a way to have the translated plain text be the outcome, instead of the namespaced: account:account:organization.invite.copyLink?

2 Answers

Use the following snippet before the describe block OR in beforeEach() to mock the needful.

jest.mock("react-i18next", () => ({
    useTranslation: () => ({ t: key => key }),
}));

Hope this helps. Peace.

use this for replace render function.


import { render, screen } from '@testing-library/react'
import DarkModeToggleBtn from '../../components/layout/DarkModeToggleBtn'
import { appWithTranslation } from 'next-i18next'
import { NextRouter } from 'next/router'


jest.mock('react-i18next', () => ({
    I18nextProvider: jest.fn(),
    __esmodule: true,
 }))

  
const createProps = (locale = 'en', router: Partial<NextRouter> = {}) => ({
    pageProps: {
        _nextI18Next: {
        initialLocale: locale,
        userConfig: {
            i18n: {
            defaultLocale: 'en',
            locales: ['en', 'fr'],
            },
        },
        },
    } as any,
    router: {
        locale: locale,
        route: '/',
        ...router,
    },
} as any)

const Component = appWithTranslation(() => <DarkModeToggleBtn />)

const defaultRenderProps = createProps()

const renderComponent = (props = defaultRenderProps) => render(
    <Component {...props} />
)


describe('', () => {
    it('', () => {

        renderComponent()
     
        expect(screen.getByRole("button")).toHaveTextContent("")

    })
})


Related