How to mock react components with react testing library?
Asked Answered
S

2

15

I have a react component, which has two children, like this:

import {Child1} from './child1';
import {Child2} from './child2';
...
return (
  <>
    <Child1 />
    <Child2 />
  </>
)

I'm using react testing-library and the app as created with create react app and not ejected. I'd like to mock them in my unit test, since they have their own tests, so I'm trying to:

jest.mock('./child1', () => 'some mocked string');
jest.mock('./child1', () => 'some mocked string');

But when I render it using import { render } from '@testing-library/react'; I see the following Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

Why is that and how do I mock those components?

Sodden answered 21/5, 2021 at 11:52 Comment(0)
C
22

child1 and child2 modules use named export to export their component. You should mock the named export component Child1 and Child2.

The below example mocks these two modules and their component with the stateless functional components.

E.g.

index.tsx:

import { Child1 } from './child1';
import { Child2 } from './child2';

import React from 'react';

export default function App() {
  return (
    <>
      <Child1 />
      <Child2 />
    </>
  );
}

child1.tsx:

import React from 'react';

export function Child1() {
  return <div>child1</div>;
}

child2.tsx:

import React from 'react';

export function Child2() {
  return <div>child2</div>;
}

index.test.tsx:

import { render } from '@testing-library/react';
import React from 'react';
import App from './';

jest.mock('./child1', () => ({ Child1: () => 'mocked child1' }));
jest.mock('./child2', () => ({ Child2: () => 'mocked child2' }));

describe('67636326', () => {
  it('should pass', () => {
    const { container } = render(<App />);
    expect(container).toMatchInlineSnapshot(`
      <div>
        mocked child1
        mocked child2
      </div>
    `);
  });
});

test result:

 PASS  examples/67636326/index.test.tsx (8.339 s)
  67636326
    ✓ should pass (25 ms)

 › 1 snapshot written.
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 written, 1 total
Time:        9.454 s
Correll answered 11/6, 2021 at 3:37 Comment(1)
I had a similar issue and it was a matter of declaring the mock outside the describe. It works now. Any explanation on why it fails (meaning it doesn't mock and renders the real component) if I bring jest.mock(...) inside the describe block?Frear
N
1

if you try to render a module.export, you should try this way

jest.mock('../components/Modal', () => () => <div>ModalMocked</div>);

in order to contribute to another solutions

Nymphalid answered 5/5, 2023 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.