【发布时间】: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