How we can iterate through buttons that have same names and click on required button

 

When we have to test applications that have a feature such as Add to Cart, we come across a scenario where multiple products each have a button and the buttons have the same name. In such as situation we need to iterate through the elements and select the required element to be clicked.

it('iterate and add first item', function () {
cy.get('.btn_inventory').each(($el, index, $list) => {
// $el is a wrapped jQuery element
if ($el.text().includes('Add to cart') && index ===0) {
cy.wrap($el).click({force:true})
cy.get('[data-test="remove-sauce-labs-backpack"]').invoke('text').then((label) =>{
expect(label).to.contain('Remove')
})
}
})
})

In the above piece of code, we have a class names .btn_inventory we then iterate through that using the cypress .each and we check if the button has a name 'Add to cart' as well as we check if its the 0th index value.

If these conditions are satisfied, we then use the cy.wrap and click on the button on the 0th index. This way we can use the .each of Cypress to iterate through the array of button elements.

As a final step to check if the button has been clicked, we check if the name of the button changes to 'Remove' once clicked.

Note: the site https://www.saucedemo.com/ was used as the reference for this post

Comments