You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Cypress动态选择静态下拉框的第二个选项

Cypress动态选择下拉框第二个选项的实现方案

核心实现代码

简洁版(直接使用索引选择)

// select方法支持传入数字索引,从0开始计数,第二个选项对应索引1
cy.get('select#segment_segment_contact_id')
  .select(1)
  // 动态校验选中值为第二个选项的value,无需硬编码
  .should('have.value', Cypress.$('select#segment_segment_contact_id option:eq(1)').val())

稳妥版(先提取属性再操作,适合需要复用属性的场景)

// 先定位到第二个option,提取对应属性后再执行操作
cy.get('select#segment_segment_contact_id option')
  .eq(1)
  .then($secondOption => {
    const optionValue = $secondOption.val()
    const optionText = $secondOption.text()
    
    cy.get('select#segment_segment_contact_id')
      .select(optionValue)
      .should('have.value', optionValue)
      // 可选校验:确认选中的选项文本匹配
      .find('option:selected')
      .should('have.text', optionText)
  })

方案说明

  • 两种实现均不依赖固定的选项文本、value属性,只要下拉框的第二个选项存在即可正常执行,适配选项内容动态变化的场景
  • 简洁版代码量少,适合仅需要完成选择操作的场景
  • 稳妥版可以提前拿到第二个选项的属性,适合后续业务逻辑需要用到对应值/文本的场景

内容的提问来源于stack exchange,提问作者Rita Basu-ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:27:03