Testing
Testing components that use react-i18next: export the plain component or test without stubbing, with an example i18next configuration for tests.
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 create a manual mock in __mocks__/react-i18next.js (picked up automatically by jest) that covers useTranslation, withTranslation and <Trans> in one place, so components mixing all three render their keys and children as plain text:
const React = require('react');
const reactI18next = require('react-i18next');
const useMock = [(k) => k, { changeLanguage: () => new Promise(() => {}) }];
useMock.t = (k) => k;
useMock.i18n = { changeLanguage: () => new Promise(() => {}) };
module.exports = {
...reactI18next,
withTranslation: () => (Component) => (props) => <Component t={(k) => k} {...props} />,
Trans: ({ children, i18nKey }) => children ?? i18nKey,
useTranslation: () => useMock,
};A more complete version of this mock (including a <Trans> mock that renders nested elements) is part of the runnable jest example: example/test-jest/src/__mocks__/react-i18next.js
Or mock it like:
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