Testing

For testing purpose of your component you should export the pure component without extending with the withTranslation hoc and test that:

export MyComponent;
export default withTranslation('ns')(MyComponent);

In the test, test the myComponent export passing a t function mock:

import { MyComponent } from './myComponent';

<MyComponent t={key => key} />

Or use https://github.com/kadirahq/react-stubber to stub i18n functionality:

const tDefault = (key) => key;
const StubbableInterpolate = mayBeStubbed(Interpolate);
const stubInterpolate = function () {
  stub(StubbableInterpolate, (props, context) => {
    const t = (context && context.t) || tDefault;
    return (<span>{t(props.i18nKey)}</span>);
  });
};

Or mock it like:

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: (i18nKey) => i18nKey };
    // or with TypeScript:
    //Component.defaultProps = { ...Component.defaultProps, t: (i18nKey: string) => i18nKey };
    return Component;
  },
}));

Or, when using the useTranslation hook instead of withTranslation, mock it like:

or, you can also spy the t function:

Testing without stubbing

Alternatively, you could also test I18next without stubbing anything, by providing the correct configuration and fully wrapping your container in the provider.

Example configuration for testing

Example test using this configuration

As translations aren't provided, this.props.i18n.language will be undefined. In case your application relies on that value you can mock resources by adding these lines to the object passed to init:

Now in your component this.props.i18n.language will return en.

Last updated