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

如何在Cypress中创建按option值选择的自定义select命令

问题根因

  • Cypress的select()方法如果传入数字类型参数,会默认按照选项的索引顺序选择,而不是匹配value属性的值,你传入的weatherLimits.Visibility.warn是数字类型的3,所以执行逻辑和预期不符。
  • 原有注释掉的断言写法错误:直接对<select>元素调用should('have.text')会匹配所有子option的拼接文本,无法正确校验选中项的文本。

调整后的自定义命令代码

Cypress.Commands.add('selectAndVerify', (selector, valueToSelect, expectedText) => {
  cy.log(valueToSelect)
  cy.get(selector)
    .should('be.enabled')
    // 转为字符串,强制按value属性匹配,避免被识别为索引
    .select(String(valueToSelect))
    // 定位到当前选中的option,校验文本
    .find('option:selected')
    .should('have.text', expectedText)
})

调用方式无需修改

沿用原有调用代码即可正常运行:

cy.selectAndVerify('[data-test="Visibility-warn"]', weatherLimits.Visibility.warn, 'Moderate/Poor');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:06:03