Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
morteza Avatar asked Nov 16 '25 00:11

morteza


1 Answers

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.

like image 67
juliomalves Avatar answered Nov 17 '25 19:11

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!