Mocking a standard npm project is straight forward. Create a __mocks__
folder adjacent to node_modules folder, then put the name of the package as the file and write the mock contents within.
Example: /__mocks__/axios.ts
Where I'm stuck on is having an npm package import that looks like this: @auth0/auth0-react
How can I mock the contents of this file? I tried creating a file named @auth0/auth0-react.tsx
but jest doesn't seem to be picking up the mocked file. When I import import { Auth0Provider } from '@auth0/auth0-react';
and console.log(Auth0Provider)
, All I get is the standard Jest.fn()
attributes.
Here are the contents of the mocked file
/* eslint-disable import/prefer-default-export */
export const Auth0Provider = (component: JSX.Element): JSX.Element => component;
Since I did not use jest.fn()
on this one method, I'm expecting console.log(Auth0Provider)
to show that it contains a function.
In my test code I have jest.mock('@auth0/auth0-react')
before my test. Any ideas?
I found the solution via another StackOverflow question by kcarra.
To summarize the answer, I'll answer it with 2 points:
The __mocks__
directory must be in the vicinity of the file being tested. If your file is under /src/MyComponent, then the path for mocks folder should be /src/__mocks__/
.
The folder structure under __mocks__
must mimc the path as shown in your import. In my scenario, I need to create a folder named @auth0
and then a file called auth0-react.tsx
in that folder.
Here's how I structured my test and mocks files.
/src/__mocks__/@auth0/auth0-react.tsx
/src/__tests__/MyComponent.tsx
/src/MyComponent.tsx