Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next-i18next Jest Testing with useTranslation

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?

like image 814
Phil Lucks Avatar asked Apr 06 '21 17:04

Phil Lucks


People also ask

Can I use react i18next in Nextjs?

Next. js has supported i18n since v10. 0.0, it allows us to set the default language, the current language in use, and the supported languages. To set locales in a Next.

Is Jest enough for testing?

Jest is a JavaScript test runner that lets you access the DOM via jsdom . While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.

Should I use enzyme with Jest?

Many people choose to use Jest and Enzyme together to test their React web applications. They use Jest as a test runner and assertion library, then use Enzyme to build the tests for their UI. This results in slimmer, cleaner testing code that's also easier to debug when a test breaks.

Can Jest be used for UI automation?

You can test the UI of React components just using the Jest testing framework, of course, but React Test Library (RTL) provides extra lightweight utility functions for Jest to work with React components, saving your time and encouraging best testing practices - it forces your application to be more accessible.


1 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.

like image 93
Mayank Gangwal Avatar answered Sep 18 '22 13:09

Mayank Gangwal