score:6

Accepted 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()
});

score:7

Spent an hour or so figuring this out myself. Problem stems from incorrect types being applied to useAuth0 after modifying mock return value. My solution was to use mocked from 'ts-jest/utils'. You can add Roles, Scope etc to user object also. (see adminUser object)

import { render, screen } from "@testing-library/react";
import { useAuth0 } from "@auth0/auth0-react";
import { mocked } from "ts-jest/utils";

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

const adminUser = {
    email: "johndoe@me.com",
    email_verified: true,
    sub: "google-oauth2|12345678901234",
    "https://<<API_URL>>/roles": ["admin", "superuser"],
};


jest.mock("@auth0/auth0-react");

const mockedUseAuth0 = mocked(useAuth0, true);

describe("TopNav Component Tests - Logged in", () => {
    beforeEach(() => {
        mockedUseAuth0.mockReturnValue({
            isAuthenticated: true,
            user,
            logout: jest.fn(),
            loginWithRedirect: jest.fn(),
            getAccessTokenWithPopup: jest.fn(),
            getAccessTokenSilently: jest.fn(),
            getIdTokenClaims: jest.fn(),
            loginWithPopup: jest.fn(),
            isLoading: false,
        });
    });
    test("Logout Button displays when logged in", () => {
        render(
                <TopNav />
        );
        const loginButton = screen.getByText(/Logout/i);
        expect(loginButton).toBeInTheDocument();
    });
    test("Make sure Admin Panel Button doesnt show without Role", () => {
        render(
                <TopNav />
        );
        const adminPanelButton = screen.queryByText(/Admin Panel/i);
        expect(adminPanelButton).toBeNull();
    });
});

describe("TopNav Component Tests - Admin User", () => {
    beforeEach(() => {
        mockedUseAuth0.mockReturnValue({
            isAuthenticated: true,
            user: adminUser,
            logout: jest.fn(),
            loginWithRedirect: jest.fn(),
            getAccessTokenWithPopup: jest.fn(),
            getAccessTokenSilently: jest.fn(),
            getIdTokenClaims: jest.fn(),
            loginWithPopup: jest.fn(),
            isLoading: false,
        });
    });
    test("Admin Panel Button displays", () => {
        render(
            <TopNav />
        );
        const adminPanelButton = screen.getByText(/Admin Panel/i);
        expect(adminPanelButton).toBeInTheDocument();
    });
});

Related Query

More Query from same tag