Unit testing using Testing Library React and Auth0Provider

Hi All,

I was looking through the forum and also the documentation for handling unit testing when consuming the react-sdk but could not find an answer. It appears that the Auth0Provider updates the state during initial render. So it will be great to get some assistance

  • Which SDK does this apply to? @auth0/auth0-react
  • Which verison of the SDK you are using? 1.0.0
  • Which version of the platform are you facing this error on? v14.0.0

App.test.js

import React from 'react'
import {render} from '@testing-library/react'
import {App} from './app'
test('renders a themed timeclock', () => {
 expect(render(<App />)).toMatchInlineSnapshot()
})

App.jsx

import React from 'react'
import {Auth0Provider} from '@auth0/auth0-react'
const App = () => (
     <Auth0Provider domain="xxxx" clientId="xxxx" redirectUri={window.location.origin}>
            <div role="timer">Hello Auth0</div>
     </Auth0Provider>
)
export {App}

Stack Trace

Warning: An update to Auth0Provider 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://fb.me/react-wrap-tests-with-act
....... more code

    console.error
      Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
 .... more code

Thanks for any help in advance.

I managed to solve the issue though it might not be the perfect solution. Auth0Provider is running something asynchronously if I did not guess wrong and it causes a re render. I was able to hack the test to get it to work but maybe there might be some best practices out there. This is the test code to get it to work. The waitFor call forces the jest runner to wait till the the div with role timer is rendered before continuing the test which fixes the error

App.test.js

import React from 'react'
import {render} from '@testing-library/react'
import {App} from './app'
test('renders a themed timeclock', () => {
  const {container} = render(<App />)
  await waitFor(() => screen.getByRole('timer'))
  expect(container).toMatchInlineSnapshot()
})

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.