I have an E-commerce application, in which i want to delete the products from my cart if anything is there before my automation tests starts(kind of cleaning up the cart before test starts). We are using cypress for test automation, i am not able to write any code for this since if-else statements are not reliable in cypress due to its Async nature. Moreover we won't be knowing how many products will be there in cart at any moment.
How can i do clean up process in this case using cypress? Right now i am making sure no products are added to cart before tests starts by manually.
Adding the code snippet:
cy.get('.Searchstyles__SearchResults-ihHuNq').then(($btn) => {
cy.log($btn.find('.MiniBasketstyles__MiniBasket-bQdyQE').length)
if ($btn.find('.MiniBasketstyles__MiniBasket-bQdyQE').length ===0) {
// do this block if there are few items in cart
cy.get('.MiniBasketstyles__Title-ddNEOV').then(($el) => {
const product = $el.text();
let products = product.split(' ');
cy.log(products[1])
const min_products = Number(products[1])
for(let i =1;i<=min_products;i++){
cy.get(':nth-child(1) > :nth-child(1) > .MiniBasketListItemstyles__CloseBtn-dyGqzc > svg > [fill="none"] > [fill="#000"]').click({force: true})
cy.wait(7000)
// closing all the items one by one
}
})
} else {
// empty else block as there it has to go to next step when there is no items in cart
}
Here even when there is no items in cart, its not going to else block rather executing if block only.
There's nothing wrong with testing a condition on the page with
if (...)
as long as you know the page is stable (not fetching data from an API).If your case I think it's ok. You have some previous tests that added data to the cart. Now at the start of the next test you want to empty the cart.
A recursive function fits this pattern
Since it takes up to 7 seconds to remove each cart item, a better strategy would be to identify how the cart is stored (by cookie perhaps?) and just destroy that cookie.
It may be that the cart isn't even stored between sessions, in which case a simple reload will work.