Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock react components with react testing library?

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?

like image 326
k102 Avatar asked Jan 25 '26 23:01

k102


2 Answers

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
like image 93
slideshowp2 Avatar answered Jan 27 '26 13:01

slideshowp2


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

like image 21
Edgar Olivar Avatar answered Jan 27 '26 11:01

Edgar Olivar