You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)'.

相关代码

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>
  )
}
....
</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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:07:39