-1

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)

Boon
  • 401
  • 1
  • 6
  • 17
  • 1
    Can you try this - `cy.xpath(NODE_PREVIEW_PANEL).children('data-testid').its('length').then((len) => { //Print Length cy.log(len) })` – Alapan Das Nov 26 '20 at 14:03
  • That kind of works, but I still have issue with mixing up sync and async code. – Boon Nov 26 '20 at 15:32
  • So what you are looking for is with iteration of `each()`, you want to push the position of the children element to the array ? – Alapan Das Nov 26 '20 at 15:44
  • the problem can be put like this - "I am getting bunch of children from the DOM which I am processing using ```each()``` function. Using the same each function I am adding it to an array. But because of ```each()``` being async, it is returning the array before it adds all the elements to the array – Boon Nov 26 '20 at 16:08

2 Answers2

1

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)
Rosen Mihaylov
  • 1,363
  • 2
  • 10
1

You can use the index value to find the position of the element. You can do something like:

cy.xpath(NODE_PREVIEW_PANEL).children('data-testid').each((el, index) => {
    //It will give the position of the element  
    Array.push(index);
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52