I’m working on E2E tests for an online store using Cypress. Right now I’m selecting products by hardcoding their names. But I want to make it more flexible.
Here’s what I’m trying to do:
- Pass the product name as a parameter
- Use that parameter to find and click the right product
The product elements on the page have a structure like this:
<div class="item-box">
<h2 class="product-title">
<a href="/product-url">Product Name</a>
</h2>
<!-- other product details -->
</div>
How can I write a Cypress command that takes a product name and clicks on the matching product? I’d like to avoid using fixed selectors if possible.
Any tips or code examples would be super helpful! Thanks in advance!
Hey SailingBreeze! I’m intrigued by your e-commerce testing challenge. 
Have you thought about using data attributes for this? It’s a neat trick I learned recently. You could add a data attribute to your product elements like this:
<div class="item-box" data-product-name="Product Name">
<!-- your existing structure -->
</div>
Then in Cypress, you could do something like:
const selectProduct = (productName) => {
cy.get(`[data-product-name="${productName}"]`).click()
}
This way, you’re not relying on text content which can be finicky sometimes. Plus, it’s super clear what each selector is for!
What do you think? Have you tried anything like this before? I’m curious to hear if you’ve explored other approaches too!
Here’s an approach that might work well for your situation:
You could create a custom Cypress command that takes a product name as an argument and uses it to locate and click the correct product. Something like this:
Cypress.Commands.add(‘clickProduct’, (productName) => {
cy.get(‘.item-box’)
.contains(‘.product-title’, productName)
.click();
});
Then in your test, you’d use it like:
cy.clickProduct(‘Your Product Name’);
This method is flexible because it searches for the product name within the product title elements, rather than relying on hardcoded selectors. It should work even if the order of products changes on the page.
Remember to add appropriate waiting or retry logic if the product list is loaded dynamically. Hope this helps with your e-commerce testing!
hey, i’ve been doing some e-commerce testing too. have you tried using cy.contains() with a wildcard? something like:
cy.contains('div.item-box', `${productName}`).click()
this way you can pass any product name as a variable. it’s pretty flexible and doesnt need hardcoded stuff. might wrok for what youre trying to do