Lukas Vis
Lukas Vis

Reputation: 475

How can I mock or spy on the custom hook variable with jest?

I am using library called react-query-firebase. The custom hook useAuthUser takes firebase auth method and manages the loading state and returns firebase auth user object.

auth is a firebase method which I think that I need to mock or spy on to make sure that its not ran.

According to jest documentation it takes 2 arguments:

jest.spyOn(object, methodName)

in that case:

jest.spyOn(auth,) and what do I put as a second argument?

And what would I do with the user variable, mock spy or what?

import { useAuthUser } from "@react-query-firebase/auth";
import { auth } from "./firebase";

function App() {
  const user = useAuthUser(["user"], auth);

  if (user.isLoading) {
    return <div />;
  }

  if (user.data) {
    return <User />;
  }

  return <div>Not signed in.</div>;
}

function User() {
  const user = useAuthUser(["user"], auth);

  return <div>Welcome {user.data.displayName}!</div>;
}

Upvotes: 0

Views: 1700

Answers (1)

Marlee BC
Marlee BC

Reputation: 33

For @react-query-firebase/auth I use jest's spyOn method.

import * as queryFirebaseAuth from '@react-query-firebase/auth';

test('should do something', () => {
  jest
    .spyOn(queryFirebaseAuth, 'useAuthUser')
    .mockImplementation(() => ({ data: { /* your user object here */ } }));
})

The spyOn method actually mocks out the whole function so you can return anything you want.

Upvotes: 1

Related Questions