1

I want to add an item in cart with a matching text like 'cashews'. I tried below code but .click() function is giving error as "bind and event handler to the click javascript event"

cy.get('.products').find('.product').each(($e1, index, $list) => {
  const textveg = $e1.find('h4.product-name').text() {
    if (textveg.includes('Cashews')) {
      $e1.find('.button').click();
    }
  }
})

can someone suggest what can be the possible reason that .click() method is not identified by cypress. I am using cypress version 7

user16695029
  • 3,365
  • 5
  • 21
vish176
  • 21
  • 5

2 Answers2

1

How you do this depends on the structure of the HTML.

It looks like you may have this sort of hierarchy

<div class="products">

  <div class="product">
    <h4 class="product-name">Almonds</h4>
    <button>Add to cart</button>
  </div>

  <div class="product">
    <h4 class="product-name">Cashews</h4>
    <button>Add to cart</button>
  </div>

</div>

Take the product section containing the text you want, and within that find the products <button>.

Your test might be

cy.contains('.product', 'Cashews')  // pick the <div class="product"> with required text
  .find('button')                   // inside the product, find it's button
  .click()
user16695029
  • 3,365
  • 5
  • 21
0

You can use .filter() to find your element and click it:

cy.get('h4.product-name').filter(':contains("Cashews")').click()
Alapan Das
  • 17,144
  • 3
  • 29
  • 52