【问题标题】:Idiomatic Cypress way to assert that two elements that contains some text exist in the DOMCypress 的惯用方式来断言 DOM 中存在两个包含某些文本的元素
【发布时间】:2021-07-23 14:19:07
【问题描述】:

使用 Cypress,对于给定的选择器(也包含一些文本)断言 DOM 中存在两个元素的惯用方式是什么?

下面是我在 JavaScript 中的做法:

Array.from(document.querySelectorAll("selector")).filter(node => node.textContent.includes("text")).length === 2

在 Cypress 中有没有一种惯用的方法来做到这一点?

我试过了:

cy.get('selector')
  .contains('text')
  .should('have.length', 2);

但我收到以下错误:

cy.contains() cannot be passed a length option because it will only ever return 1 
element.

【问题讨论】:

    标签: cypress


    【解决方案1】:

    您可以像这样将filter()contains() 结合使用。 (Cypress Docs)

    cy.get('selector')
      .filter(':contains("text")')
      .should('have.length', 2);
    

    【讨论】:

      【解决方案2】:

      或者,您可以使用以下不带“过滤器”选项的方法。

      例子:

      <table>
        <tbody>
          <tr>
            <td>Same</td>
            <td>Same</td>
            <td>Different</td>
            <td>Same</td>
          </tr>
        </tbody>
      </table>
      
      
      // selects all table cells with text "Same"
      cy.get('td:contains("Same")').should('have.length', 3)
      // if the text does not have white spaces, no need to quote it
      cy.get('td:contains(Same)').should('have.length', 3)
      // you can find elements NOT having the given text
      cy.get('td:not(:contains(Same))')
        .should('have.length', 1)
        .and('have.text', 'Different')
      

      阅读更多here

      【讨论】:

        猜你喜欢
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        • 2022-10-19
        • 2015-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多