Is there an elegant way of writing a cypress test to find if the z-index of all children elements lies within a specific range(ex: 200-299)?

258 views Asked by At

Given a div, is there an elegant way to find if the z-index values of all the children elements of the div are within a specific range.(ex: 200-299). So for the given example code, I need to test if the div with class name childDivClass & image with class name imgClass are within a z-index range of 200 to 299.

<div class="rootDivClass">
 <div class="childDivClass">
  <img class=imgClass">
  </img>
 </div>
</div>
1

There are 1 answers

0
SuchAnIgnorantThingToDo-UKR On

The general way to calculate an element's z-index is

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

You can check the parent and children separately, using a function to extract the 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)
  })

I don't think there's an easy way to get a parent element and all it's children in one selection, but you could add a custom command

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