如何使用反应测试库模拟反应组件?

时间:2021-05-21 11:52:27

标签: reactjs testing jestjs mocking react-testing-library

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

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

为什么会这样,我如何模拟这些组件?

1 个答案:

答案 0 :(得分:0)

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