是否有一种优雅的方法来编写 cypress 测试来查找所有子元素的 z-index 是否位于特定范围内(例如:200-299)?

Sun*_*nny 2 html testing z-index getcomputedstyle cypress

给定一个 div,是否有一种优雅的方法来查找该 div 的所有子元素的 z-index 值是否在特定范围内(例如:200-299)。因此,对于给定的示例代码,我需要测试类名为childDivClass 的div和类名为imgClass的图像是否在200299的 z-index 范围内。

<div class="rootDivClass">
 <div class="childDivClass">
  <img class=imgClass">
  </img>
 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Suc*_*UKR 6

计算元素的一般方法z-index

cy.get('some-selector')
  .then($el => {
    return window.getComputedStyle($el[0]).getPropertyValue('z-index')
  })
Run Code Online (Sandbox Code Playgroud)

您可以使用函数提取z-index.

function zIndex($els) {
  return [...$els].map(el => {
    return window.getComputedStyle(el).getPropertyValue('z-index')
  })
}

cy.get('.childDivClass')
  .then(zIndex)                    // extracts z-index as string value
  .then(Number)                    // converts to number
  .should('be.within', 200, 299)

cy.get('.childDivClass')
  .children()
  .each($child => {
    cy.wrap($child)
      .then(zIndex)
      .then(Number)
      .should('be.within', 200, 299)
  })
Run Code Online (Sandbox Code Playgroud)

我认为没有一种简单的方法可以在一次选择中获取父元素及其所有子元素,但您可以添加自定义命令

Cypress.Commands.add('addChildren', {prevSubject:true}, (subject) => {
  return subject.add(subject.children())
})

cy.get('.childDivClass')
  .addChildren()
  .each($el => {
    cy.wrap($el)
      .then(zIndex)
      .then(Number)
      .should('be.within', 200, 299)
  })

Run Code Online (Sandbox Code Playgroud)