So I apologize if this question is a bit trivial, but I’ve been combing the deocs looking for help and I’m still stuck.
I have a custom React hook called “useTranslator” that I use in some React components to translated strings into other languages. useTranslator
is built on top of a custom i18N library my team uses.
Okay, so I’m working on writing some test for my React components using Jest. Since I want to isolate this library I just need to mock one function in it that comes from useTranslator". It's a name export and I assign it to the function named
translate()`.
The component looks like this
import { useTranslator } from "../../../stores/i18nStore";
const DialogBox = ({open, handleClose, closeBtnText, handleConfirm, confirmBtnText , title, children}: DialogBoxProps) => {
const translated = useTranslator();
closeBtnText = closeBtnText ?? translated("js.dialog_default_cancel");
confirmBtnText = confirmBtnText ?? translated("js.dialog_default_confirm");
So here’s the problem I’m having is that Jest can’t find the function named translated()
because I’m not sure how I’m supposed to mock it.
All I need Jest to do is return a string with whatever is pass into translated().
I want to check that "js.dialog_default_cancel"
or "js.dialog_default_confirm"
is now what is render into the Dom.
So far my test looks like this
import { useTranslator } from "../../../stores/i18nStore";
jest.mock('../../../stores/i18nStore', () => ({
useTranslator: () => {},
}))
test("Dialog Box", () => {
it('renders default text strings', () => {
render(
<DialogBox
title="Test Dialog"
open={true}
handleClose={()=>{}}
handleConfirm={()=>{}}>
Test Dialog Message 3
</DialogBox>
)
const dialogComp = screen.getByText("Test Dialog");
expect(dialogComp).toBeInTheDocument()
})
When I run it I get this error message.
console.error
Error: Uncaught [TypeError: translated is not a function]
How do I tell Jest this i function and i want it to just return me what ever string I pass into it.
Thanks