0

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/>) })

4
  • 1
    see jestjs.io/docs/manual-mocks#mocking-user-modules Commented Aug 25, 2021 at 4:41
  • Show the code. What have you tried? What did you get? Commented Aug 25, 2021 at 9:57
  • @slideshowp2 child component has a lot of logic that needs to be mocked, but i dont want to repeat testing it in it's own test and when testing parent Commented Aug 25, 2021 at 10:05
  • It's not clear. You can mock the complex child component when testing the parent component. Commented Aug 25, 2021 at 10:26

1 Answer 1

1

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({...});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.