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

问题描述 投票:0回答:1

我是一名初学者,正在为我的工作编写第一个测试。

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

我可以看到 realhover() 做了一些事情,改变了按钮的颜色,但我总是收到错误:

预期 具有值为 rgb(182, 222, 251) 的 CSS 属性 background-color,但该值为 rgb(207, 233, 252)

// 获取链接按钮第一张卡悬停前后的颜色 cy.get('.g-card__item-link') .should('have.css', 'background-color', 'rgb(207, 233, 252)') //悬停前的颜色

cy.get('.g-card__item-link') .realHover() .should('have.css', 'background-color', 'rgb(182, 222, 251)') //我应该在悬停时得到这个颜色

hover cypress
1个回答
0
投票

浏览器有一个 CSS 引擎,可以计算某些事件的样式更改,例如

hover
。这会更改可见渲染,但不会更改 DOM 中的 CSS 属性,这就是为什么在测试中after悬停后返回相同的颜色。

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

来自 MDN 的示例:悬停页面

<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>

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

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)

这些步骤可以包含在自定义命令中,可以通过添加到

cypress/support/commands.js

使其成为全局命令
Cypress.Commands.add('computedStyles', {prevSubject: 'element'}, ($el, prop) => {
  return window.getComputedStyle($el[0])[prop]
})

cy.get('button')
  .realHover()
  .computedStyles('background-color')
  .should('eq', colors.bisque)
© www.soinside.com 2019 - 2024. All rights reserved.