2

We have 5 elements and we need to match the text of all 5 elements with some expected text.

Say //div[@class="xyz"] is the common element selector and for 1st element we need to use (//div[@class="xyz"])[1], and so-on using a for-loop.

for (i=0; i<xyz.length; i++) {
  cy.get('(//div[@class="xyz"])[i]')
}

How can I do this in Cypress?

Fody
  • 23,754
  • 3
  • 20
  • 37

3 Answers3

1

Maybe you want .eq() command?

cy.get('(//div[@class="xyz"])').eq(i)
Fody
  • 23,754
  • 3
  • 20
  • 37
1

In a Cypress test a for-loop is implemented with .each()

const expectedText = ['a', 'b', 'c', 'd', 'e']
cy.xpath('(//div[@class="xyz"]')
  .each(($el,index) => {
    expect($el.text()).to.eq(expectedText[index])
  })

or

const expectedText = ['a', 'b', 'c', 'd', 'e']
cy.get('div.xyz')
  .each(($el,index) => {
    expect($el.text()).to.eq(expectedText[index])
  })
TesterDick
  • 3,830
  • 5
  • 18
0

You can use a forEach loop to iterate over the texts. And in the XPath, you can use the index values from the forEach loop. Something like:

var textArray = ['text1', 'text2', 'text3', 'text4', 'text5']

for (let [index, text] of textArray.entries()) {
  cy.xpath(`//div[@class="xyz"])[${index}]`).should('have.text', text)
}

And in case you just have one text that you want to validate for the 5 elements, you can use the traditional for loop with 5 iterations something like:

for (let i = 0; i < 5; i++) {
  cy.xpath(`//div[@class="xyz"])[${i}]`).should('have.text', 'some text')
}
Alapan Das
  • 17,144
  • 3
  • 29
  • 52