MockedAuth0Provider for testing in jest
See original GitHub issueMockedAuth0Provider for testing
Hopefully this is an appropriate place to post this, but I’ve been banging my head against the wall for a few days now trying to find the best way to test my react app which is wrapped in the Auth0Provider
The problem seems to be with the Auth0Client
and some of the checks it does before initializing, mainly around validating that window.crypto
exists. I’ve tried to mock out the Auth0Client
similar to what is done in this repo in __mocks__/@auth0
however I still haven’t been able to get around this error. Uncaught [Error: For security reasons, window.crypto is required to run auth0-spa-js.]
In my tests i have a custom render
function that imports import { Auth0Provider } from "@auth0/auth0-react";
and returns:
return <Auth0Provider clientId="__test_client_id__" domain="__test_domain__">
<Provider store={store}>
<MockedProvider mocks={[getUserMock, ...mocks]} addTypename={false}>
<UserProvider>{children}</UserProvider>
</MockedProvider>
</Provider>
</Auth0Provider>
I’ve seen a few suggestions of people recommending to set a global window.crypto
in setUpTests.js
but this still seems like it could be avoided with a mocked provider.
Describe the ideal solution
Have a MockedAuth0Provider
that doesn’t do the check for window.crypto
or provide a way to pass a mocked Auth0Client
as a prop to the Auth0Provider
.
Alternatives and current work-arounds
The only current work around that I have seen is to define a crypto property on the window object.
I’m a React and Jest novice so if this isn’t a valid request I apologize, but I’ve exhausted all the options that I could find to solve this problem. Any tips on how to get the Auth0Provider
mocked out properly would be greatly appreciated.
Thanks
Issue Analytics
- State:
- Created 2 years ago
- Reactions:5
- Comments:6 (2 by maintainers)
I think it’d be helpful if Auth0 shipped with a mock provider much like Apollo does. Using
jest.mock
in every test file is a lot of duplication. As far as I can tell, there’s no way in jest to push that out to a helper method that gets called. Moreover, due to the way Jest hoists mocks, I can’t see a way to test two different mocked responses within the same test file. Having to split component tests out into multiple files based on auth state is going to be rather annoying.That leaves @kcarra’s suggestion of using setupTests.ts. That addresses the duplication issue, but only works for a single auth state. I’ve worked out a way to conditionally change the response based on some closed over state with external control, but that amounts to having a global control flag, so tests can’t run in parallel.
Having an official solution with accompanying documentation would be very helpful.
Thank you very much @adamjmcgrath! This solved my problem, I ended up putting all the mocks for auth0 in the setupTests.js file