Skip to content

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 {
} from "react-auth0-spa";
const user = {
  email: "[email protected]",
  email_verified: true,
  sub: "google-oauth2|12345678901234"
// intercept the useAuth0 function and mock it
describe("First test", () => {
  beforeEach(() => {
    // Mock the Auth0 hook and make it return a logged in state
      isAuthenticated: true,
      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!


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;
  isAuthenticated: true,
  logout: jest.fn(),
  loginWithRedirect: jest.fn()