tonyrocks
tonyrocks

Reputation: 609

How do I click on a link that is associated to a another DIV with Cypress.io?

I'm having a problem locating an item to click that is related to a specific "row" in a div using the .click() function in Cypress.io. Below is my example div table:

<div class="table"> 
  <div class="col-sm-10">Item 1</div>
  <div class="col-sm-2 action">
    <a href="#"><i class="fa-times-circle-o"></i></a>
  </div>

  <div class="col-sm-10">Item 2</div>
  <div class="col-sm-2 action">
    <a href="#"><i class="fa-times-circle-o"></i></a>
  </div>
</div>

What I want to do is click on the A link for a specified row. For example, I want to click on the A link for the "row" that contains the text of Item 2. I need to do this dynamically because the order of the items, as well as the names of the items, may change depending upon data.

I'm trying something like this:

cy.get('div:contains("Item 2")').click()

But the div is not the clickable one, it is the following A in the code. Any ideas?

Upvotes: 3

Views: 7667

Answers (2)

Sergio Gragera
Sergio Gragera

Reputation: 816

cy.contains('div', 'Item 2').next().find('a').click()

Upvotes: 5

wscourge
wscourge

Reputation: 11281

According to Best Practices | Cypress - Selecting elements, the best way to do it is using dedicated data-cy attribute for your cypress tests, and then, within the tests, using CSS attribute selectors.

Best Practice: Use data-* attributes to provide context to your selectors and insulate them from CSS or JS changes.

In your case, I would do it this way:

<div class="table"> 
   <div class="col-sm-10">Item 1</div>
   <div class="col-sm-2 action">
    <a href="#"><i class="fa-times-circle-o"></i></a>
   </div>
   <div class="col-sm-10">Item 2</div>
   <div class="col-sm-2 action">
    <a href="#" data-cy="item-2-anchor"><i class="fa-times-circle-o"></i></a>
   </div>
</div>

cy.get('[data-cy="item-2-anchor"]').click();

I strongly recommend doing it this way project-wide, as it guarantees working tests despite any changes made to other attributes (id, class, href ..) under development.

Upvotes: 5

Related Questions