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: <...

问题:

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?


回答1:

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.


回答2:

cy.contains('div', 'Item 2').next().find('a').click()
  • 发表于 2019-01-08 09:45
  • 阅读 ( 214 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除