You need to enable JavaScript to run this app. React Testing Library fireEvent触发hover后样式未更新问题求解
优惠活动
大模型
产品
解决方案
定价
更多

React Testing Library fireEvent触发hover后样式未更新问题求解

问题原因
  • 事件触发不匹配:你组件上监听的是onMouseEnter事件,但测试中调用的是fireEvent.mouseOver,两个事件逻辑不对应,无法触发状态更新
  • 未等待异步更新:React状态更新是异步的,且react-pose的动画执行存在延时,触发事件后立即读取样式时还没完成更新,自然拿不到预期结果

修复后的测试代码

基础fireEvent版本

import { waitFor } from '@testing-library/react'

it('BigTile hover check', async ()=>{
    const { container } = render(<BigTile />)
    const elem = container.querySelector<HTMLElement>('.MuiPaper-root')
    if (!elem) fail("Element is null.")
    // 触发组件实际绑定的mouseEnter事件
    fireEvent.mouseEnter(elem);
    // 异步等待动画执行、样式更新完成
    await waitFor(() => {
        expect(elem.style.transform).toBe('scale(1.05)')
    })
})

更推荐的userEvent版本(更贴近真实用户操作)

import userEvent from '@testing-library/user-event'

it('BigTile hover check', async ()=>{
    const user = userEvent.setup()
    const { container } = render(<BigTile />)
    const elem = container.querySelector<HTMLElement>('.MuiPaper-root')
    if (!elem) fail("Element is null.")
    
    // 测试hover效果
    await user.hover(elem)
    expect(elem.style.transform).toBe('scale(1.05)')
    
    // 可补测鼠标移出的还原逻辑
    await user.unhover(elem)
    expect(elem.style.transform).toBe('scale(1)')
})

代码优化建议
  1. 冗余变量清理:组件中定义的style变量实际没有使用,可以直接删除
  2. 样式逻辑性能优化:当前styleProducer每次组件渲染都会重新生成makeStyles实例,性能损耗大。可以利用MUI makeStyles原生支持接收props参数的特性,把样式配置提到组件外部,避免重复生成:
// 把固定配置提到组件外部
const colorMap = {
  default: { tile: {} },
  grey: { tile: { background: grey[700], color: 'white' } },
  green: { tile: { background: green[300] } },
  teal: { tile: { background: teal[400], color: 'white' } },
  blue: { tile: { background: lightBlue[200] } },
} as const

const useStyles = makeStyles((theme: Theme) => ({
  tile: (props: {variant: BigTileProps['variant'], color: BigTileProps['color']}) => {
    const sizeMap = {
      small: {minWidth: theme.spacing(10), height: theme.spacing(10), background: grey[500]},
      default: {minWidth: theme.spacing(15), height: theme.spacing(15)},
      big: {minWidth: theme.spacing(20), height: theme.spacing(20)},
      large: {minWidth: theme.spacing(25), height: theme.spacing(25)},
    }
    return {
      ...sizeMap[props.variant],
      position: 'relative',
      '&:hover': { cursor: 'pointer' },
      ...colorMap[props.color].tile
    }
  },
  content: {
    fontSize: '2rem',
    fontWeight: 'bold'
  },
  title: {
    textTransform: 'uppercase'
  },
  icon: {
    position: 'absolute',
    top: 0,
    left: 0
  }
}))

// 组件内调用
const BigTile: React.FC<BigTileProps> = ({
    variant = 'default',
    color = 'default',
    ...rest
}) => {
    const [hover, setHover] = React.useState(false)
    // 直接传参数获取样式,不用动态生成makeStyles
    const classes = useStyles({variant, color})
    // 其余逻辑保持不变
}
  1. 类型优化:把代码里的any替换为MUI官方的Theme类型,提升类型安全性
  2. 测试稳定性优化:给PosedPaper添加data-testid="big-tile"属性,测试时用getByTestId选择元素,避免MUI类名变化导致测试失效
  3. 依赖替换:react-pose已经停止维护,可以换成同团队的framer-motion,维护更积极、API兼容度高

内容的提问来源于stack exchange,提问作者mhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 02:12:03