How to use react-intl with jest

Viewed 5921

I'm working with React Testing Library an I need to get the translation for a text, we mocked in our setupTest file the react-intl library:

jest.mock('react-intl', () => {
  const reactIntl = require.requireActual('react-intl');
  const intl = reactIntl.createIntl({
    locale: 'en'
  });

  return {
    ...reactIntl,
    useIntl: () => intl
  };
});

but I don't know how to use it in the test, could someone provide me an complete examble of a test using the library to get a translation, please? I tried to do it in this way:

let intl = useIntl();
      let i18n = {
        header: intl.formatMessage({
          id: 'header.myHeader',
          defaultMessage: 'header.myHeader'
        })
      };

but there are any messages in intl from the locales.

Regards.

1 Answers

Don't mock it, try and directly wrap your component with IntlProvider, or even better, create a helper render where you wrap with IntlProvider and render it with that:

import {IntlProvider} from 'react-intl`;
import {render} from '@testing-library/react';

const renderWithReactIntl = (component, locale, messages) => {
  return render(<IntlProvider locale={locale} messages={messages}>
                 {component}
                </IntlProvider>
  );
};

Within your test() or it() just wrap your unconnected component in renderWithReactIntl:

const { /testing library selector goes here/ } 
  = renderWithReactIntl(<YourComponent />, messages, locale)
Related