Pablo Jurado

15 June, 2021

How to mock react custom hooks

When testing components that utilize custom hooks, we might need to mock their implementation.

The following component has a custom hook useAuth that returns true or false depending if the user is authenticated

import useAuth from "hooks/useAuth";

function HomePage() {
  const isAuthenticated = useAuth();

  if (isAuthenticated) {
    return "Welcome user!";
  } else {
    return "Please login.";
  }
}

We can mock the useAuth hook and change the isAuthenticatedMock variable for testing the different behaviors.

let isAuthenticatedMock = false;

jest.mock("./hooks/useAuth", () => {
  return () => isAuthenticatedMock;
});