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

如何在Cypress中根据默认值选择下拉框的非默认选项?

Cypress实现随机默认值下拉框的切换测试

场景说明

我有如下HTML下拉控件:

<select id="answer">
    <option value="yes"> Yes </option>
    <option value="no"> No </option>
    <option value="maybe"> Maybe </option>
</select>

页面加载时会随机选中其中一个选项,无法提前预知默认值。需要编写Cypress测试完成以下逻辑:

Given the select control is visible
When I select a different option
Then the selected option is updated

核心需求是实现类似伪代码的逻辑:

cy.get('select').select(~~ any option that isn't the default value ~~)

实现代码

可以通过Cypress的DOM操作方法,先获取默认选中值,再筛选并选择非默认选项,具体实现如下:

方法一:先获取默认值再筛选选项

cy.get('#answer')
  // 获取当前默认选中的value
  .invoke('val')
  .then(defaultValue => {
    // 获取所有选项的value并过滤掉默认值
    cy.get('#answer option').then($options => {
      const alternativeOptions = [...$options].map(opt => opt.value).filter(val => val !== defaultValue)
      // 选择第一个非默认选项(也可以用Math.random()随机选)
      cy.get('#answer').select(alternativeOptions[0])
    })
    // 验证选中值已更新
    cy.get('#answer').invoke('val').should('not.equal', defaultValue)
  })

方法二:直接筛选非默认选项并选择

cy.get('#answer').then($select => {
  const defaultValue = $select.val()
  // 定位第一个非默认值的选项并选择
  const newOption = $select.find(`option[value!="${defaultValue}"]`).first().val()
  cy.get('#answer').select(newOption)
  // 断言选中值与默认值不同
  cy.get('#answer').invoke('val').should('not.eq', defaultValue)
})

测试运行流程

以两个示例说明执行逻辑:

  • 示例1:页面加载默认选中'No'(value='no')

    1. Cypress获取默认值'no'
    2. 筛选出'yes'、'maybe'两个选项,选择第一个'yes'
    3. 验证当前选中值为'yes',与默认值'no'不同
  • 示例2:页面加载默认选中'Maybe'(value='maybe')

    1. Cypress获取默认值'maybe'
    2. 筛选出'yes'、'no'两个选项,选择第一个'yes'
    3. 验证当前选中值为'yes',与默认值'maybe'不同

内容的提问来源于stack exchange,提问作者user9847788

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:24:23