Search code examples
cypressproductcart

Cypress - How to add multiple items to the cart from product page?


I am new to cypress and learning automation tool.I have a question related to the product page, I need to add few items to the cart. I added a code with each loop. The problem is when Add to cart button gets clicked for one item, the page goes to the cart page not remains on the product page. How can I add other items to the cart. I tried with back command, that's not working. Please help, thanks!

Cypress.Commands.add("selectproduct", (productname) => { 
    
    cy.get ('.productCard').each(($el,index,$list) =>{
        if ($el.text().includes (productname)) {
            cy.get('.btn.btn-secondary.ghost.btn-primary').eq(index).click() 

Solution

  • The back button should work, but perhaps you need to confirm the page changes, for example

    Cypress.Commands.add("selectproduct", (productname) => { 
        
        cy.get ('.productCard').each(($el,index,$list) =>{
            if ($el.text().includes (productname)) {
                cy.get('.btn.btn-secondary.ghost.btn-primary').eq(index).click()
                cy.contains('Shopping cart page title')  // confirm the shopping cart shows
                cy.go('back')
                cy.contains('Product page title')  // confirm the product page shows