如何使用React测试库(React Testing Library)模拟React组件?

12

我有一个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。这是为什么,我该如何模拟这些组件?
2个回答

19

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

3
我曾遇到类似的问题,解决方法是在describe外部声明模拟对象。现在它能正常工作了。 关于为什么当我将jest.mock(...)放在describe块内时会失败(即无法模拟并呈现真实组件),请问是否有任何解释? - Fazwelington

1

如果你尝试渲染一个module.export,你应该尝试这种方式

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

为了贡献于其他解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接