Search code examples
reactjsreact-hooksreact-testing-libraryreact-hooks-testing-library

Testing return value of a custom hook


I am trying to write a test suit for this custom hook.

export const useInitialMount = () => {
  const isFirstRender = useRef(true);

  // in the very first render the ref is true, but we immediately change it to false.
  // so the every renders after will be false.
  if (isFirstRender.current) {
    isFirstRender.current = false;
    return true;
  }
  return false;
};

Very simple returns true or false.
As I saw, I should use @testing-library/react-hooks and here is my try:

test("should return true in the very first render and false in the next renders", () => {
  const { result } = renderHook(() => {
    useInitialMount();
  });
  expect(result.current).toBe(true);
});

but I got undefined which doesn't make sense it should be either true or false.

PS: the code works as expected on the project.


Solution

  • The syntax for the renderHook call is not quite right in your test.

    Note the curly brackets, you should return useInitialMount() from renderHook callback, not just call it inside it (hence why you get undefined).

    test('should return true in the very first render and false in the next renders', () => {
      const { result } = renderHook(() => useInitialMount());
      expect(result.current).toBe(true);
    });
    

    Edit: To clarify, the difference here is that:

    Calling () => { useInitialMount(); }); returns undefined, there are no return statements so the function will return undefined by default.

    But calling () => useInitialMount() (which is short syntax for () => { return useInitialMount(); }) will return the value of calling the hook.

    Reference: Arrow Functions > Functions body.