howard wolowitz
howard wolowitz

Reputation: 628

How to mock imported component in Reactjs

I need to write test for a wrapper component which holds children <Example/> component. And there is a heavy mocking going on in <Example/>. What I am trying to achieve is to put mocked <Example/> inside <Parent/> without having to do mocking stuff again.

pseudo code test('test', () => { //there somehow need to swap component that is imported inside Parent render(<Parent/>) })

Upvotes: 0

Views: 1772

Answers (1)

Florian Motteau
Florian Motteau

Reputation: 3714

If you are using functional components, you can mock children components by adding this code at the top of your test file :

// Each occurrence of ChildComponent in the tested component
// will be mocked with a div, with a data-testid attribute and
// its props in a data-props attribute
jest.mock('/path/to/child/ChildComponent', () => ({
  __esModule: true,
  ChildComponent: (props: any) => (
    <div data-testid="mocked-child-component" data-props={JSON.stringify(props)}>
      Mocked Child Component
    </div>
  ),
}));

So you can test that ChildComponent exists when testing the parent component, by searching for the data-testid (or the text in the div), and check that the props passed to ChildComponent by the component under test are correct :

const getProps = (element: HTMLElement): Record<string, unknown> => JSON.parse(element.getAttribute('data-props'));

[...]

// check that parent component is passing correct props to its child
rtl = render(<ParentComponent />));
expect(getProps(rtl.getByTestId('mocked-children-component'))).toEqual({...});

Upvotes: 1

Related Questions