Search code examples
javascripteachcypresschildren

count number of children returned and push the children attribute into array using Cypress


I am trying to count the number of children returned when doing

cy.xpath(NODE_PREVIEW_PANEL).children('data-testid')

So that I can use the count to pass all the values into an array sequentially avoiding the async of .each() function.

How can I get the count of children here?

(or you can suggest a totally different solution)


Solution

  • One way I use successfully is to use reference variable

    let variablesToValidate = {
        numberOfChildren: 0,
        attributes: []
    }
    cy.xpath(NODE_PREVIEW_PANEL)
        .children('data-testid')
        .each(($element, index, $array) =>{
            cy.wrap($element)
                .should('have.attr', 'attributeName')
                .then(atrributeValue => variablesToValidate.attributes.push(atrributeValue))
        })
        .then($array => variablesToValidate.numberOfChildren = $array.length)