Testing custom hooks that are using next-i18next useTranslation hook

Viewed 24

I have created a custom hook that returns the translated value using the useTranslation hook.

    import { useTranslation } from "next-i18next";

    export const useCustomHook = (data) => {
      const {t, i18n: { language: locale }} = useTranslation();

      const value = {
            field: t("some.key.from.json.file", { arg: data.arg }),
            field2: data.name,
            field3: t("another.key", {
                arg: data.arg2, count: 3
            })
        }
      return value;
    };

I want to create a unit test for this custom hook, but I can't get the useTranslation hook to work as it does when running the app itself. Further info my current setup is as follows:

1- I'm using Nextjs with next-i18next library. 2- No i18n provider to wrap the app, only using HOC from next-i18next to wrap _app. 3- I have 2 json files for locales.

Is there a way to allow the useTranslation hook to work and get the parsed value from the translation file? here's what I tried so far too:

1- mocking the useTranslation hook, but this returns the ("another.key") as is without the parsed value. 2- I tried to create a wrapper with i18n-next provider, but that didn't work too.

Here's my test file.

    describe("useCustomHook()", () => {
      it("Should return correctly mapped props", () => {
        const { result } = renderHook(() =>
        useCustomHook(mockData)
        );

        const data = result.current[0];
        expect(data.field).toBe(mockData.field); // this returns ("some.key.from.json.file") it doesn't use the t function,
        // ... //
    });
0 Answers
Related