When testing a component that calls useUser in a jest runner with react-testing-library, there's an error about Warning: An update to null inside a test was not wrapped in act(...).
console.error
Warning: An update to null inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at Object.<anonymous>.exports.default (/Users/tommyfritz/workspace/bugs/jest-auth0-nextjs-bug/node_modules/@auth0/nextjs-auth0/src/frontend/use-user.tsx:134:3)
There would be no error at all, clean run.
The bug can be seen by cloning the following repo and running yarn, yarn test.
https://github.com/flapjackfritz/jest-auth0-nextjs-issue
version: 1.4.0
framework: jest, react-testing-library, Nextjs
ARM64 OSX
Node 16.1.0
Hello @flapjackfritz,
I had this problem few days ago, you have to wrap your component that uses the useUser hook with the UserContext and pass your mocked values in the _value_ prop.
import { UserContext } from '@auth0/nextjs-auth0'
...
const checkSession = jest.fn()
it("Should display user name 'Valentin' when user is connected", async () => {
render(
<UserContext.Provider value={{ user: { name: 'Valentin' }, isLoading: false, checkSession }}>
<NavBar />
</UserContext.Provider>
)
await waitFor(() => {
expect(screen.queryByText('Valentin')).toBeInTheDocument()
})
})
I hope this can help you !
Thanks @LunarzFR! @flapjackfritz let me know if that resolves your issue
The docs said to use import { UserProvider } from '@auth0/nextjs-auth0';
Why would that not be what you use in the tests? I'm setting up the contexts in my code this way, to test it I have to figure out an entire other way to set it up?
https://github.com/auth0/nextjs-auth0/blob/main/src/frontend/use-user.tsx#L43
@adamjmcgrath yes, that did clear the error.
@flapjackfritz Yes it's possible to use UserProvider but you have less control on event like _isLoading_. I prefer to use UserContext.Provider to test all cases.
it("Should display user name 'Valentin' when user is connected", async () => {
render(
<UserProvider user={{ name: 'Valentin' }}>
<NavBar />
</UserProvider>
)
await waitFor(() => {
expect(screen.queryByText('Valentin')).toBeInTheDocument()
})
})
Great, thanks for your help @LunarzFR
@flapjackfritz - closing this, feel free to ping me if you'd like me to reopen
Also, check out the nextjs-auth0 sample app that uses react-testing-library https://github.com/auth0-samples/auth0-nextjs-samples/blob/main/Sample-01/tests/pages/profile.test.jsx#L9