reactjs 如何用react测试库模拟react组件?

neskvpey  于 2023-05-06  发布在  React
关注(0)|答案(2)|浏览(110)

我有一个react组件,它有两个孩子,像这样:

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

我使用的是react testing-library,应用程序是用create react app创建的,没有弹出。我想在我的单元测试中模拟它们,因为它们有自己的测试,所以我试图:

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

但是当我使用import { render } from '@testing-library/react';渲染它时,我看到了下面的Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined
为什么会这样?我如何模拟这些组件?

3pvhb19x

3pvhb19x1#

child1child2模块使用命名导出来导出其组件。您应该模拟命名导出组件Child1Child2
下面的示例使用无状态功能组件模拟这两个模块及其组件。
例如:
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>
    `);
  });
});

测试结果:

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
js4nwp54

js4nwp542#

如果您尝试呈现一个modul.export,您应该尝试这种方法

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

以促成另一种解决方案

相关问题