0

I'm aware of this, but it's not my case.

Example:

<AuthProvider>
  <SessionProvider>
    <AnotherProvider>
      <OneMoreProvider>
        <MyComponent />

All of these providers are actually regular React Components with state and effects, that fetch some data via GraphQL and pass that data as a 'value' prop to MyContext.Provider in return statement.

This enforces me to create lots of mocks for modules that are being used in all of these providers, just to render my own component in testing env.

Any thoughts about what can be done to avoid creating so many mocks?

cule111
  • 49
  • 1
  • 9

1 Answers1

1

You can create a helper test lib with a custom render function that wrap your component with the contexts then export all react testing library methods from there

- test/lib.jsx

import React from 'react';
import { render as reactRender } from '@testing-library/react';
export * from '@testing-library/react';

export const render = (MyComponent, options) => {
    return reactRender(
        <AuthProvider>
            <SessionProvider>
                <AnotherProvider>
                    <OneMoreProvider>
                        {MyComponent}
                    </OneMoreProvider>
                </AnotherProvider>
            </SessionProvider>
        </AuthProvider>,
        options
    )
}

Then use this helper lib to import test functions instead of using @testing-library/react directly


import { render } from 'test/lib'
import MyComponent from './MyComponent';

test("My component", () => {
    const { getByTestId, ... } = render(<MyComponent>);
    ...
});
mamod
  • 504
  • 3
  • 6