【问题标题】:Cypress - Click checkbox that depends on the value of another checkbox on a table赛普拉斯 - 单击取决于表格上另一个复选框的值的复选框
【发布时间】:2021-05-05 07:10:39
【问题描述】:

我有一个包含 2 列复选框的表格。

我想点击右侧选中值的第一个复选框。 注意:左侧的所有复选框均未禁用,右侧的所有复选框均已禁用。

编辑: 我的 DOM 看起来像这样:

<table>
  <thead>
    <tr>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    {items.map(item) => (
        <tr>
          <td>
            <input type="checkbox" />
          </td>
          <td>
            <input type="checkbox" checked={item.posted} disabled />
          </td>
        </tr>
      )
    }
    
  </tbody>
</table>

来自 api 的数据重申了这就是为什么复选框的选中状态是动态的

【问题讨论】:

  • 你能分享你的 HTML DOM 吗?
  • @AlapanDas 更新我的问题
  • 行数会根据API调用结果而变化吗?

标签: reactjs material-ui cypress


【解决方案1】:

尝试找到第一个选中的,然后移动到第一个复选框

cy.get('input:checked')       // all checked inputs
  .eq(0)                      // first one
  .parent('td')               // move to cell
  .prev()                     // previous cell
  .find('input')              // it's input 
  .click()

为了阐明如何正确使用.each(),您需要使用第三个参数collectionreturn false,以避免检查右侧选中的每一行。

cy.get('input[type="checkbox"]')
  .each(($ele, index, collection) => {
    if ($ele.is(':checked')) {
      cy.wrap(collection).eq(index-1).click()
      return false;                       // break early to only click the first
    }
  })

【讨论】:

  • 我正在使用材质 ui,所以我不得不使用父母('td')。我也尝试使用 .each 并且效果很好,你能解释一下它为什么有效吗,比如 wrap 和 eq(index-1) 是如何工作的
  • 其实我是在澄清错误,但.eq()是选择多个元素时的赛普拉斯索引方法。 .get() 返回所有input 元素(按照它们在页面上出现的顺序)并将它们放入collection 参数中,.wrap() 只是使collection.eq() 一起工作。因此,选中第一个之前的input 就是您要点击的那个。
  • 它可以更简单——只需使用collection[index-1].click(),不需要wrap().eq()——我之前没有注意到。
【解决方案2】:

您尝试这样的操作,遍历所有复选框,一旦您找到禁用的复选框,您可以使用.eq(index-1) 转到上一个复选框,然后执行click()

cy.get('input[type="checkbox"]').each(($ele, index) => {
    if ($ele.is(":disabled")) {
        cy.wrap($ele).eq(index-1).click()
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多