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