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

React-jss样式异常:单元测试未触发hover却应用hover样式

React-JSS 组件样式测试异常排查

问题场景

使用 react-jss(版本 ^9.8.7)为组件应用样式时,测试发现未触发 hover 状态,但组件的 background-color 却显示为 hover 样式定义的 rgba(255, 255, 255, 0.4),而非默认的 rgba(255, 255, 255, 0.2)。

相关代码

组件返回代码

return (
  <div id={id} className={rootClassName} onClick={disabled ? noop : onClick}>
    {content}
  </div>
)

测试用例代码

test('check if button have correct styles when the scheme prop is ghost', () => {
  const { container } = render(<Button scheme='ghost' title='button' />)

  const button = container.firstChild
  const styles = window.getComputedStyle(button)

  console.log('style', styles)
})

Ghost 方案对应的样式定义

ghostRoot: {
  minHeight: 42,
  lineHeight: '42px',
  borderRadius: 5,
  border: 'none',
  paddingLeft: 20,
  paddingRight: 20,
  backgroundColor: 'rgba(255, 255, 255, 0.2)',
  '&:hover': {
    backgroundColor: 'rgba(255, 255, 255, 0.4)',
  },
  '&$withIcon': {
    paddingRight: 16,
  },
},

问题原因分析及解决方向

  1. JSS 嵌套选择器编译异常
    JSS 9.x 版本存在嵌套伪类选择器的编译 bug,可能导致 &:hover 被错误编译为普通类选择器(而非 .ghostRoot:hover),使得 hover 样式直接覆盖默认背景色。可通过查看页面生成的 CSS 代码确认选择器是否正确。

  2. 测试环境样式计算问题
    若使用 jsdom 作为测试环境,它本身不支持伪类状态的样式计算。如果 getComputedStyle 返回 hover 样式,大概率是样式被错误编译为非伪类规则,而非真实触发了 hover。

  3. 类名冲突或样式合并问题
    检查 rootClassName 是否包含多个类名,是否有其他全局样式或组件样式中的规则覆盖了默认背景色。可在测试中打印 button.className 确认类名组成。

  4. 组件逻辑误触发状态
    排查组件代码中是否存在手动添加 hover 类名、修改元素状态的逻辑,导致样式被错误应用。

解决建议

  • 优先升级 react-jss 到 10.x 及以上版本,修复旧版本的嵌套选择器 bug。
  • 打印生成的 CSS 规则和元素类名,确认样式选择器的正确性。
  • 若需在测试中验证伪类样式,可使用 @testing-library/jest-dom 的 toHaveStyle 配合模拟伪类状态的工具。

内容的提问来源于stack exchange,提问作者hamid-beigi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:27:42