testing-library / react-hooks-testing-library

🐏 Simple and complete React hooks testing utilities that encourage good testing practices.
https://react-hooks-testing-library.com
MIT License
5.25k stars 230 forks source link

`renderHook` result with `vitest` and `react@18` always returns `null` #971

Closed amir-deriv closed 5 months ago

amir-deriv commented 5 months ago

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:

image

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

GerroDen commented 5 months ago

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

amir-deriv commented 5 months ago

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)