Skip to content
Advertisement

React: How to mock Auth0 for testing with Jest

I’m using React(react-create-app and TypeScript). Login is made with Auth0.

I want to write tests with Jest, and I found this ressource which is basically the only thing around that speaks about Mocking the Auth0 object.

So my code looks like this:

import React from "react";
import ReactDOM from "react-dom";
import TopBar from "./index";
import {
  useAuth0
} from "react-auth0-spa";

const user = {
  email: "johndoe@me.com",
  email_verified: true,
  sub: "google-oauth2|12345678901234"
};

// intercept the useAuth0 function and mock it
jest.mock("react-auth0-spa");

describe("First test", () => {
  beforeEach(() => {
    // Mock the Auth0 hook and make it return a logged in state
    useAuth0.mockReturnValue({
      isAuthenticated: true,
      user,
      logout: jest.fn(),
      loginWithRedirect: jest.fn()
    });
  });

  it("renders without crashing", () => {
    const div = document.createElement("div");
    ReactDOM.render( < TopBar / > , div);
  });
});

But I end stuck with this error:

Property 'mockReturnValue' does not exist on type '() => IAuth0Context | undefined'.ts(2339)

I’m a bit lost here, any help would be greatly appreciated!

Advertisement

Answer

It’s a TypeScript error. You will need to type the mocked useAuth0 as the original type does not have a method called mockReturnValue. Something like this should work:

const mockedUseAuth0 = <jest.Mock<typeof useAuth0>>useAuth0;

mockedUseAuth0.mockReturnValue({
  isAuthenticated: true,
  user,
  logout: jest.fn(),
  loginWithRedirect: jest.fn()
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement