React18+TypeScript项目Jest测试出现Function components cannot be given refs警告
React 18 + Jest测试中MaterialUI组件的Ref警告问题
环境配置
- React 18
- 最新版本webpack、babel、typescript、jest
- MaterialUI组件库
问题现象
项目运行、构建均无错误,但在执行Jest组件测试时,出现如下警告:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Check the render method of 'ForwardRef(Rating)'.
相关代码
Menu.tsx组件代码
import React from 'react'; import Button from '@mui/material/Button'; import Stack from '@mui/material/Stack'; type MyProps = { increment: () => void decrement: () => void clear: () => void } export default function Menu(props: MyProps){ return( <Stack direction="row" spacing={2}> <Button className="qa-increment" variant="contained" onClick={props.increment}>Display Additional Provider</Button> <Button className="qa-decrement" variant="contained" onClick={props.decrement}>Remove Provider</Button> <Button className="qa-clear" variant="contained" onClick={props.clear}>Clear Providers</Button> </Stack> ) }
Menu父组件代码片段
.... </Typography> <Menu increment={() => {this.increaseCount()}} decrement={() => {this.decreaseCount()}} clear={() => {this.clearCount()}} /> <Grid container spacing={5}> ....
Jest组件测试代码
import React from 'react'; import renderer from 'react-test-renderer'; import Menu from './Menu'; describe('it checks the Card component', () => { it('Checks against the component snapshot', () => { const tree = renderer .create(<Menu/>) .toJSON(); expect(tree).toMatchSnapshot(); }); });
排查进展
- 查阅过相关技术帖子,但因刚接触React/Jest及TypeScript与React的集成,不确定现有方案是否适配当前环境
- 尝试过使用
jest.mock()、用React.forwardRef()包裹renderer函数,但未成功(可能用法有误) - 最新排查:确认问题与MaterialUI组件相关,移除MaterialUI改用原生HTML5元素后,警告不再出现,正在进一步定位具体原因
内容的提问来源于stack exchange,提问作者Andrew Pavlick
相关产品推荐
相关产品推荐

