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

React Testing Library中userEvent.hover不生效如何解决?

问题原因

测试失败主要是三个常见问题导致的:

  • 你给Info组件设置了transition: all 0.5s ease过渡动画,hover触发后opacity不会立刻变为1,测试立刻断言只会拿到初始值0
  • @testing-library/user-event v14及以上版本的所有交互方法都是异步的,你没有加await等待hover操作执行完成,断言时机早于样式生效时机
  • 原生toHaveStyle无法准确识别styled-components嵌套伪类触发的子元素样式,需要配合适配包增强检测能力

解决步骤

  1. 先安装styled-components对应的样式测试适配依赖:
npm install jest-styled-components --save-dev
  1. 修改测试文件逻辑,将测试改为异步,加上交互等待逻辑,适配后的代码如下:
import userEvent from '@testing-library/user-event'
import "@testing-library/jest-dom/extend-expect";
import 'jest-styled-components'
import { waitFor } from '@testing-library/react'
import ProductItem from "./ProductItem";

test("Check Product Hover", async () => {
  const user = userEvent.setup() // v14+版本需要先初始化user实例,低版本可省略该行
  const { getByTestId } = render(
    <ProductItem item={{ id: 7, img: "https://i.imgur.com/aYMvzlX.png" }} />
  );
  const productContainer = getByTestId("productContainer");
  const productInfo = getByTestId("productInfo");

  await user.hover(productContainer)
  // 等待过渡动画完成后再断言
  await waitFor(() => {
    expect(productInfo).toHaveStyle("opacity:1");
  })
});

如果你不想在测试里等待过渡时间,可以给测试环境全局禁用所有过渡动画,或者单独修改Info组件的样式,测试环境下将transition设为none即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:36:04