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

Cypress测试如何等待元素移除selectionAdded类解决用例不稳定问题

问题核心原因

你的代码有两个核心错误导致稳定性差:

  • 遍历判断类的逻辑错误:each回调拿到的element是jQuery实例,直接调用.not("have.class", "selected")是jQuery的元素过滤方法,不是Cypress断言,判断逻辑完全失效,大概率会选到不符合要求的按钮。
  • 等待逻辑完全不对:你最后写的oddsSelectionElements.oddsButton().not("have.class", "selectionAdded")是筛选所有按钮里没有该类的元素,没有加断言等待,也没有绑定到你刚刚点击的那一个按钮上,只要有任意一个按钮符合条件就会直接向下执行,根本等不到目标按钮的selectionAdded类移除。
修改后的代码
const oddsSelectionElements = new OddsSelectionElements();

When ("User selects an available bet bundle selection", () => {
  // 直接筛选未选中的第一个按钮,替换冗余的each循环逻辑
  oddsSelectionElements.oddsButton()
    .filter(':not(.selected)')
    .first()
    .as('targetButton') // 将目标按钮存为别名,后续直接复用
    .then(($targetBtn) => {
      // 保存选项名称
      oddsSelectionElements.selectionName()
        .eq($targetBtn.index())
        .invoke('text')
        .then(formatters.formatString)
        .as('selectionName');
      // 点击目标按钮
      cy.wrap($targetBtn).click();
    })

  // 专门等待刚才点击的目标按钮状态符合要求,超时时间可根据前端实际响应速度调整
  cy.get('@targetButton')
    .should('not.have.class', 'selectionAdded', { timeout: 10000 })
    .and('have.class', 'selected');
})

class OddsSelectionElements {
    oddsButton() {
        return cy.get('.button__bet')
    }
    // 注意你原有代码调用的selectionName方法未在类中定义,自行补充即可
}
export default OddsSelectionElements
修改说明
  • 用Cypress内置的.filter(':not(.selected)')直接过滤未选中的按钮,避免手动遍历的判断错误,逻辑更简洁可靠。
  • 将目标按钮存为别名,后续等待逻辑只针对这一个被点击的按钮判断,不受其他按钮状态干扰。
  • 用.should('not.have.class', 'selectionAdded')做断言,Cypress会自动轮询等待条件成立,超时时间可自定义,完全解决提前向下执行的问题。
  • 额外新增have.class selected的断言,双重确认按钮已经进入可再次点击的状态,进一步提升用例稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:12:03