How to unit test @auth0/auth0-react

Hi I’m using @auth0/auth0-react library

I flowed the tutorial The Complete Guide to React User Authentication with Auth0
https://auth0.com/blog/complete-guide-to-react-user-authentication/#Set-Up-the-Auth0-React-SDK

my problem is with unit testing of the Profile component

import React from “react”;
import { Container, Row, Col } from “react-bootstrap”;
import { Highlight, Loading } from “…/components”;

import { useAuth0, withAuthenticationRequired } from “@auth0/auth0-react”;

const Profile = () => {
const { user } = useAuth0();
const { name, picture, email } = user;

return (



Profile


{name}


{email}





{JSON.stringify(user, null, 2)}


);
};

export default withAuthenticationRequired(Profile, {
onRedirecting: () => ,
});

in this code example, I can never test the component because in the unit test I get the Loading component -

How can mock user is Authenticated = true with a mock auth0 provider so I can the component

Thank you

1 Like

Here is an example. The simplest approach is to stub the withAuthenticationRequired method:

import {render} from '@testing-library/react';
import Profile from './Profile';

jest.mock("@auth0/auth0-react", () => ({
    withAuthenticationRequired: jest.fn().mockImplementation((component, ignore) => component)
}))

test('renders profile view', () => {
    const rendered = render(<Profile/>);
    const sectionHeading = rendered.container.querySelector("#profile-section-heading")
    expect(sectionHeading).toBeInTheDocument()
});

afterEach(() => jest.clearAllMocks())
1 Like

Thanks for sharing it with the rest of community!