I'm trying to test a component, here's the component, simplified:
const Block = () => {
const { t } = useTranslation();
return <p data-testid="text">{t('some.text')}</p>;
}
Then I have this test:
test('That the text is correct', () => {
const wrapper = render(
<I18nextProvider i18n={i18n}>
<Block />
</I18nextProvider>
);
expect(wrapper.getByTestId('text')).toHaveTextContent('Hello!');
});
The i18n is my config file, which looks like this:
i18n
.use(Backend)
.use(initReactI18next)
.init({
fallbackLng: 'en',
lng: 'en'
debug: false,
react: {
useSuspense: false,
},
interpolation: {
escapeValue: false,
},
});
But I'm still getting:
Expect element to have text content:
Hello!
Received:
some.text
My suspicion is that the Backend plugin is what's making it not work.
I solved this issue simply by importing the i18n configuration file im my test.
First I tried the documentation but would still get the same error. Finally, after some fixes my test works and it looks like that:
import {render, screen} from '@testing-library/react'
import myComponent from "path/to/MyComponent";
import "path/to/i18n";
describe('MyComponent', () => {
it('should render input with placeholder', () => {
render(<MyComponent/>);
const placeholderItem = screen.getByPlaceholderText('translation');
expect(placeholderItem).toBeInTheDocument();
})
}
An the component looks like this:
import * as React from 'react';
import {useTranslation} from 'react-i18next';
export default function MyComponent() {
const {t} = useTranslation();
return (<Input placeholder={t("key") ?? ''}/>);
}
So, the game changer for me was to import the "path/to/i18n" i18n configuration file in my test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With