`renderHook` result with `vitest` and `react@18` always returns `null`
amir-deriv opened this issue · 2 comments
vitest: 1.3.1@testing-library/react: 14.2.1react: 18.2.0node: 18.16.0npm(oryarn): 9.5.1
Relevant code or config:
describe("useTranslations hook", () => {
test("localize from hook must work fine", () => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<TranslationProvider defaultLang="EN" i18nInstance={i18nInstance}>
{children}
</TranslationProvider>
);
const { result } = renderHook(() => useTranslations(), {
wrapper,
});
expect(result.current.localize("test")).toEqual("test");
});
});useTranslations.ts
import { useTranslation } from "react-i18next";
import { useContext } from "react";
import { TranslationContext } from "@/provider/index";
import { str as crc32 } from "crc-32";
export default function useTranslations() {
const instanceValue = useContext(TranslationContext);
const options = useTranslation();
const localize = (tString: string, values: Record<string, unknown> = {}) =>
options.t(crc32(tString).toString(), { defaultValue: tString, ...values });
if (!instanceValue) {
throw new Error(
"useTranslation has to be used within <TranslationContext.Provider>"
);
}
return {
...options,
localize,
switchLanguage: instanceValue.switchLanguage,
currentLang: instanceValue.currentLang,
};
}What you did:
I am trying to write test cases for this hook useTranslations, but I always get the result from renderHook as { current: null }
What happened:
Problem description:
I am trying to test the hook useTranslations, but I always get the result as null. I have tried adding logs into the function body of useTranslations and the values are logging just as fine. The only problem is whatever I am returning I am not getting in the result key of renderHook and it's always returning null
I am using vitest and react@18 and @testing-libarary/react@14 so renderHook is coming from the testing library.
Can anyone help me identify what could be the issue here ? Thanks
This could also be my problem right now.
jest: 29.7.0
@testing-library/react-hooks: 8.0.1
react: 18.2.0
react-dom: 18.2.0
node: 18.19.1
yarn: 4.0.2
[edit]
nvm I see i have to upgrade to @testing-library/react
Update:
It was my wrapper which was causing the issue :)
I was returning the null inside my Provider (wrapper) if the values are not loaded.
if (!i18nInstance || !isTranslationsLoaded) return null;I fixed it by using await waitFor(() => result.current.localize)