top of page

React Testing V - [Providers]

Sometimes you may work with third-party component libraries like MUI. It might have a wrapper component that wraps our whole App component. Mostly in cases of Redux, we need to wrap it with the store provider.

Most wrapping component is on the parent component (Redux wrapper wraps the whole react app component), or the MUI theme provider wraps the whole app.

We will see the <themeprovider> wrap in MUI for testing. Before that, you install the MUI library using npm or yarn.

Then I created Mui Typography to display the current mode in MuiHeading.js

When you write a test, the expected value would be 'dark,' but the received value would be 'light.'

  • This is because the test is run in a simulation environment.

  • RTL and Jest provide this environment.

  • They mimic the Dom.

  • In a real browser, the component is wrapped with <Themeprovider>; hence <App> and its children can access the configured theme in MuiProviders.js.

So you get this in the browser,

  • Since the testing file is in simulation, it cannot access the provider/wrapper.

  • By default, the Mui theme is 'light' for all components and their children.

  • Hence, the actual value is 'light'

Hence the 'light' will pass

What to do now to access the providers/wrappers?

We need to give providers/wrappers while the component renders. So we give it in the render method.

The 'render' method takes in the second argument --> { wrapper: your wrapper }

We cannot pass in the wrapper every time we render in the test. Isn't it nice to have a single place where context providers/wrapper is connected, and we can use it in every test file?

Yes! there is provision to it.

Welcome to the custom render function:

You can copy the code from here - testing-library

Create a file called - test-utils.js

Make it look like this

Now we will remove the second argument in the test file for the wrapper.

You get this error because we still import from '@testing-library/react' and not from 'test-utils.js'

Now the test will pass,

bottom of page