无法在 realhover() 上获取 css 背景颜色良好值

1 hover cypress

我想在悬停按钮时验证真实颜色。

我可以看到realhover()它的作用,改变按钮的颜色,但我总是收到错误:

预期<a.g-card__item-link>CSS 属性值为background-colorrgb(182, 222, 251)但该值是rgb(207, 233, 252)

测试代码为:

// get link button 1st card hover color before and after
cy.get('.g-card__item-link')
  .should('have.css', 'background-color', 'rgb(207, 233, 252)') //color before hover

cy.get('.g-card__item-link')
  .realHover()
  .should('have.css', 'background-color', 'rgb(182, 222, 251)')  //I should get this color on hover
Run Code Online (Sandbox Code Playgroud)

Tes*_*ick 8

浏览器有一个 CSS 引擎,可以计算某些事件的样式更改,例如hover. 这会更改可见渲染,但不会更改 DOM 中的 CSS 属性,这就是悬停测试中返回相同颜色的原因。

要获取计算样式,请使用Window: getCompulatedStyle() 方法

来自 MDN 的示例:hover 页面

<style>
  .joinBtn {
    width: 10em;
    height: 5ex;
    background-color: gold;
    border: 2px solid firebrick;
    border-radius: 10px;
    font-weight: bold;
    color: black;
    cursor: pointer;
  }

  .joinBtn:hover {
    background-color: bisque;
  }
</style>

<p>Would you like to join our quest?</p>
<button class="joinBtn">Confirm</button>
Run Code Online (Sandbox Code Playgroud)

可以按如下方式进行测试:

const colors = {
  gold: 'rgb(255, 215, 0)',
  bisque: 'rgb(255, 228, 196)'
}

const computedStyles = ($el) => window.getComputedStyle($el[0])

cy.get('button')
  .should('have.css', 'background-color', colors.gold) 

cy.get('button')
  .realHover()
  .then(computedStyles)          // call getComputedStyle()
  .its('background-color')       // pick out background-color value
  .should('eq', colors.bisque)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


这些步骤可以包含在自定义命令中,可以通过添加来使其成为全局命令cypress/support/commands.js

Cypress.Commands.add('computedStyle', {prevSubject: 'element'}, ($el, prop) => {
  return window.getComputedStyle($el[0])[prop]
})

cy.get('button')
  .realHover()
  .computedStyle('background-color')
  .should('eq', colors.bisque)
Run Code Online (Sandbox Code Playgroud)

查找可悬停元素的示例

来自w3schools - How TO - Hoverable Dropdown实时演示页面,

CSS:hover规则针对的是<div class="dropdown">而不是<button>元素。

您可以通过开发工具、样式面板并交互式检查各种元素的悬停效果来找到答案。

在此输入图像描述