Testing return value of a custom hook

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply