【问题标题】:jest.mock on React Functional component - nothing was returned from renderjest.mock on React Functional 组件 - 渲染没有返回任何内容
【发布时间】:2021-03-25 16:51:50
【问题描述】:

我使用干净的 Create React App 实例和 React 测试库

$ npx create-react-app test-app
...
$ npm install --save @testing-library/react @testing-library/jest-dom

然后我创建简单的功能组件

./Chleb.js:

import React from 'react';

const Chleb = () => <div>chleb</div>;

export default Chleb;

在默认 App.js 中:

import React from 'react';
import Chleb from "./Chleb";

function App() {
  return (
    <div className="App">
      <Chleb />
    </div>
  );
}

export default App;

然后,在 App.test.js 中:

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

jest.mock('./Chleb');

describe('<App /> tests', () => {
  it('Should render the component correctly', () => {
    const {container} = render(<App/>);
    expect(container).toMatchSnapshot();
  });
});

什么产出:

Error: Chleb(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

我认为 Jest 或 RTL 都不支持箭头函数?

这真的很奇怪,但是当我将 Chleb.js 转换为旧的 React Class 组件时,它可以正常工作。 当我在 jest.mock('...', fn) 中提供手动 fn 模拟实现时,它也可以工作。

是否需要为 React 功能组件提供手动模拟实现,或者这是某种错误?

【问题讨论】:

  • 你找到解决办法了吗?
  • 嘿@Anders 不,我们对所有模块进行了手动模拟:(

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


【解决方案1】:

尝试在 jest 配置中将 resetMocks 设置为 false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 2020-09-02
    • 2020-11-27
    • 2018-04-05
    • 2020-07-24
    • 2020-09-14
    • 2021-07-03
    • 2021-01-01
    相关资源
    最近更新 更多