【问题标题】:Selecting cypress elements that do not contain text with Cypress使用 Cypress 选择不包含文本的 cypress 元素
【发布时间】:2021-06-15 13:42:53
【问题描述】:

我正在进行一项测试,该测试会遇到包含无效选择的下拉列表。下拉菜单不会禁用这些,您可以单击它们,它们只是显示产品的“不可用”。

<select readonly="" class="size-selector">
  <option value="">Size</option>
  <option value="XS">XS</option>
  <option value="S">S - Unavailable</option>
  <option value="M">M - Unavailable</option>
  <option value="L">L</option>
  <option value="XL">XL</option>
</select>

我希望能够选择Size 之后不包含文本“不可用”的第一个选项。

【问题讨论】:

    标签: typescript cypress


    【解决方案1】:

    赛普拉斯提供.filter() 和相反的.not() 来过滤列表。

    cy.get('option')
      .not(':contains("Unavailable")')      // exclude Unavailable
      .not(':contains("Size")')             // exclude list header
      //.not('[value=""]')                  // alternative way to exclude list header
      .eq(0)                                // take the first
      .invoke('text')                       // get the text
      .then(firstAvailableOption => {
        cy.get('select.size-selector')
          .select(firstAvailableOption)     // use text to select option
      })
    
    cy.get('select.size-selector')
      .invoke('val')
      .should('eq', 'XS')
    

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:使用each() 循环浏览下拉列表中的选项字段。现在使用text() jquery 方法检查每个选项的内部文本。找到元素后,使用cy.select() 选择元素。

      cy.get('select.size-selector option').each(($ele) => {
          if (!($ele.text().includes('Unavailable') || $ele.text().includes('Size'))) {
              cy.get('select.size-selector').select($ele.text())
              return false; // Needed to break each loops in Cypress
          }
      })
      

      【讨论】:

      • 这太复杂了,请参阅下面的简单赛普拉斯命令来做同样的事情。
      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 2022-10-23
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      相关资源
      最近更新 更多