React Testing Library中userEvent.hover不生效如何解决?
问题原因
测试失败主要是三个常见问题导致的:
- 你给
Info组件设置了transition: all 0.5s ease过渡动画,hover触发后opacity不会立刻变为1,测试立刻断言只会拿到初始值0 @testing-library/user-eventv14及以上版本的所有交互方法都是异步的,你没有加await等待hover操作执行完成,断言时机早于样式生效时机- 原生
toHaveStyle无法准确识别styled-components嵌套伪类触发的子元素样式,需要配合适配包增强检测能力
解决步骤
- 先安装styled-components对应的样式测试适配依赖:
npm install jest-styled-components --save-dev
- 修改测试文件逻辑,将测试改为异步,加上交互等待逻辑,适配后的代码如下:
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
相关产品推荐
相关产品推荐

