I have an application that uses Redux and react-i18next for translating the string. I want to write a unit test that will interpolate the i18n object in a human-readable format so that I can test the string as 'Sign in with Google' instead of 'login.sign_in_with_google'. The application was bootstraped with "Create React App". The i18n interpolations work without any problems when the application is actually running. I have to use the <Suspense />
component, otherwise, it doesn't mount the component.
The project tree:
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── locales
│ │ └── en
│ │ └── translation.json
└── src
├── i18n
│ └── i18n.js
Component sample:
const Login = (props) => {
const { t } = useTranslation();
return (
<Button>{t('login.sign_in_with_google')}</Button>
)
}
Test sample:
test('Login with Google button is rendered', async () => {
// Mount the component
const { getByText } = render(
<Suspense fallback={<div>Loading...</div>}>
<I18nextProvider i18n={i18n}>
<Login {...props} />
</I18nextProvider>
</Suspense>,
);
expect(getByText(i18n.getDataByLanguage('en').login.sign_in_with_google)).toBeDefined();
await waitFor(() => expect(screen.getByText(('Sign in with Google'))).toBeInTheDocument());
});
What I'm getting here is that the component is mounted, but the button string is not interpolated as an i18n object. The bottom line is, I need to convert i18n keys into human-readable format so that I can test the component properly.
translation.json file:
{
"login": {
"sign_in_with_google": "Sign in with Google",
},
}
When I try to log i18n.getDataByLanguage('en')
it returns undefined.