【问题标题】:Dynamic selection of 2nd item from a static dropdown using cypress使用柏树从静态下拉列表中动态选择第二个项目
【发布时间】:2021-11-04 11:17:12
【问题描述】:

要自动化 CRUD 功能,我需要从静态下拉列表中选择第二项,html 就像

<select name="segment[segment_contact_id]" id="segment_segment_contact_id">
   <option value="73082">Rita Basu</option>
   <option value="73349">researcher user</option>
</select>

所以通过使用 cypress,我使用的是硬编码值,我的代码就像

const segmentUser2 = 'researcher user'
const userValue2 = 73349
cy.get('select#segment_segment_contact_id')
  .select(segmentUser2)
  .should('have.value', userValue2)

我需要建议,因为我不喜欢使用硬编码值,而是希望始终动态使用下拉列表中的第二项。

【问题讨论】:

    标签: javascript cypress ui-automation


    【解决方案1】:

    你可以这样做

    Cypress.Commands.add(
      'selectNth',
      { prevSubject: 'element' },
      (subject, pos) => {
        cy.wrap(subject)
          .children('option')
          .eq(pos)
          .then(e => {
            cy.wrap(subject).select(e.val())
          })
      }
    )
    

    用法

    cy.get('[name=assignedTo]').selectNth(2)
    

    【讨论】:

    • 我可以得到一个函数形式的例子,只是不想为它创建一个自定义命令。
    • 这是一个更清晰的测试。有了一个函数,你就可以放松链接了。
    【解决方案2】:

    您也可以使用它。首先,我们使用eq() 命令获取列表中第二项的值。然后,一旦我们获得了值,我们只需将其传递给 select()

    cy.get('select#segment_segment_contact_id option').eq(1).invoke('val')
      .then((val) => {
        cy.get('select#segment_segment_contact_id').select(val)
      })
    

    如果您只想验证值或文本,您可以这样做:

    cy.get('select#segment_segment_contact_id option')
      .eq(1).should('have.value', 73349)
    cy.get('select#segment_segment_contact_id option')
      .eq(1).should('have.text', 'researcher user')
    

    【讨论】:

      【解决方案3】:

      这是@ItsNotAndy 没有自定义命令的方式。

      cy.get('select#segment_segment_contact_id')
        .children('option').eq(1)
        .then($option => {
          cy.wrap($option).parent().select($option.val())
        })
      

      作为一个函数

      function selectNth(selector, pos) {
        cy.get(selector)
          .children('option').eq(pos)
          .then($option => {
            cy.wrap($option).parent().select($option.val())
          })
      }
      
      selectNth('select#segment_segment_contact_id', 1)
      

      通过显示的文本进行验证

      cy.get('select#segment_segment_contact_id')
        .find(':selected')
        .contains('researcher user')
      

      通过 selectedIndex 验证

      cy.get('select#segment_segment_contact_id')
        .its('0.selectedIndex')
        .should('eq', 1)
      

      【讨论】:

        猜你喜欢
        • 2018-06-29
        • 1970-01-01
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多