【问题标题】:How to find button element in a table grid如何在表格网格中查找按钮元素
【发布时间】:2021-11-25 09:37:11
【问题描述】:

我是柏树的新手。 我有一个用户表,每一行都有编辑按钮。我想通过电子邮件查找特定用户,然后单击该行中的编辑按钮。您能帮我找到 Cypress 测试的编辑按钮吗?

【问题讨论】:

    标签: cypress getelementsbytagname findelement


    【解决方案1】:

    比这更容易。

    您可以使用.contains() 找到正确的行(<tr> 而不是<td>)。

    然后在该行中找到<a>

    cy.contains('tr', 'Joei Smithi')  // whichever bit of text id's them, 
                                      // but specify 'tr' as the element
                                      // Checks all the row children, but returns the row
      .find('a')                      // Now find() looks only in that row, and any depth
      .click()                        // hit it 
    

    【讨论】:

      【解决方案2】:

      您可以使用 data-* 属性为您的选择器提供上下文,并将它们与 CSS 或 JS 更改隔离开来。

      在您的 html 文件中:

      <a data-cy={uniqueId}>Edit</button>
      

      在您的 cypress 测试文件中:

      cy.get('[data-cy=${uniqueId}]').click()
      

      为什么要使用这个?

      向元素添加 data-* 属性为我们提供了一个仅用于测试的目标选择器。

      data-* 属性不会因 CSS 样式或 JS 行为变化而改变,这意味着它不会与元素的行为或样式耦合。

      另外,它让每个人都清楚,这个元素是由测试代码直接使用的。

      来源:best practices from official cypress doc

      【讨论】:

        【解决方案3】:

        所以你可以做这样的事情。首先,获取电子邮件的父行tr,然后在该行中,获取编辑按钮并单击它。

        cy.contains('td', 'joe9.smith@yourdomain.co.nz')
          .parent('tr')
          .children('td')
          .find('a')
          .click()
        

        【讨论】:

          【解决方案4】:

          你可以试试下面的代码,

          1. 首先我们会找出您的电子邮件索引

          2. 然后在 EDIT 按钮中应用索引

            let position = 0;
            cy.get('table > tr').should(($eachTr) => {
            let count  = $eachTr.length;
                for(let i=0; i<count; i++ ){
                    const text = $eachTr.text();
                    if(text.includes('your email')){
                        position = i;
                    }
                }
            });
            
            cy.contains('EDIT').eq(position).click();
            

          【讨论】:

            猜你喜欢
            • 2013-04-26
            • 1970-01-01
            • 2014-09-04
            • 1970-01-01
            • 1970-01-01
            • 2014-05-25
            • 1970-01-01
            • 2015-11-26
            • 1970-01-01
            相关资源
            最近更新 更多