'i18n.exists is not a function while testing via jest / react-testing library
I am using react testing library along with Jest. I am not able to mock exists function in test script.
Below is my code.
errorComponent.js
import { useTranslation } from "react-i18next";
export default function Error(props) {
const { t, i18n } = useTranslation();
return (
<div>
{i18n.exists(props.errorText) ? t(props.errorText) : props.errorText}
</div>
)
}
myComponent.js
import { useTranslation } from "react-i18next";
export default function Error(props) {
return (
<div>
<Input value="" id="testig-input"/>
<Error
errorText={'XYZ'}
/>
</div>
)
}
myTestFile.test.js
const temp= document.querySelector(`input[id='testig-input']`);
fireEvent.change(temp, { target: { value: '' } });
When I try to execute this I am getting error saying that "i18n.exists is not a function". I tried to mock but its not working. Anyone kindly help me to remove this.
Solution 1:[1]
In your code, you should have an <I18nextProvider> wrapping everything being translated somewhere. When you run the jest test, you need to render the component wrapped in the same way:
render(
<I18nextProvider i18n={myConfig}>
<MyComponent />
</I18nextProvider>
)
Alternatively, can try to mock the exists function, but it is better to more closely mimic how your app is actually run.
import * as i18next from "react-i18next";
jest.spyOn(118next, 'useTranslation').mockReturnValue({
t: (val) => val,
i18n: { exists: () => true }
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HaveSpacesuit |
