Reputation: 139
I am struggling iterating through elements in an array using cypress/typescript. I am logging everything great and able to see each index and what it shows but I am still returning the entire array vs the actual index and two days later I cannot figure out how to grab the actual index [0], [1], [2], etc. I have a tried a lot of things but this is what I have as my latest try. Thanks for any help ending my suffering!
sportPage.getFirstCard().within(() => {
sportPage.getSecondSection().within(() => {
sportPage
.getMyCoolType()
.should('exist')
.each(($item, $index) => {
cy.wrap($item)
.invoke('text')
.then((text) => {
if ($index !== 0) values.push(text);
cy.log($index.toString());
cy.log(text);
});
})
.then(() => expect(values.toString()).to.equal('Yoga');
});
});
});
});
Upvotes: 3
Views: 8516
Reputation: 1610
To test the individual texts in the array of elements returned by .getMyCoolType()
,
sportPage.getFirstCard().within(() => {
sportPage.getSecondSection().within(() => {
sportPage
.getMyCoolType()
.should('exist')
.each(($item, $index) => {
cy.wrap($item)
.invoke('text')
.then((text) => {
cy.log($index.toString());
cy.log(text);
if ($index !== 0) {
expect(text.trim()).to.equal('Yoga');
}
});
})
});
});
Or to test all items after the loop
sportPage.getFirstCard().within(() => {
sportPage.getSecondSection().within(() => {
sportPage
.getMyCoolType()
.should('exist')
.each(($item, $index) => {
cy.wrap($item)
.invoke('text')
.then((text) => {
if ($index !== 0) values.push(text);
cy.log($index.toString());
cy.log(text);
});
})
.then(() => expect(values.every(item => item === 'Yoga')).to.equal(true) );
});
});
You might also get away with this
sportPage.getFirstCard().within(() => {
sportPage.getSecondSection().within(() => {
sportPage
.getMyCoolType()
.should('exist')
.then(($items) => {
const texts = [...$items].map(item => item.text()); // map elements into texts
return texts.slice(1); // ignoring the first one
})
.then((items) => expect(items.every(item => item === 'Yoga')).to.equal(true) );
});
});
Upvotes: 2