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

Cypress中基于按钮启用/禁用状态的条件判断代码失效问题求助

问题分析与解决方案

你的问题核心在于对jQuery集合的:disabled选择器判断逻辑理解有误,导致分支判断完全反了。咱们一步步拆解:

为什么之前的代码不工作?

当你用cy.get('voyage-suggested-routes').find('button.selectButton')获取到多个按钮时,$routes是一个jQuery元素集合。此时调用$routes.is(":disabled"),jQuery的规则是:只要集合中有任意一个元素匹配选择器,就返回true。

也就是说,哪怕有1个按钮是启用的,只要其他按钮是禁用的,$routes.is(":disabled")还是会返回true,直接进入"No existing routes found"分支——这和你的实际需求完全相反。

而你尝试的$routes.is(":disabled").length === 0更不对,因为.is()返回的是布尔值,布尔值没有length属性,undefined === 0会被判定为false,还是走错误分支。

修正后的代码逻辑

你的需求是:只要存在至少一个启用的selectButton,就执行删除操作;如果所有selectButton都禁用,才走无路由分支。

对应的正确判断应该是检查集合中是否有启用的按钮,用$routes.not(":disabled").length > 0来判断:

cy.get('voyage-suggested-routes')
  .find('button.selectButton')
  .then(($routes) => {
    // 检查是否有启用的按钮
    const hasEnabledRoutes = $routes.not(":disabled").length > 0;
    if (hasEnabledRoutes) {
      cy.log("Deleting......")
      cy.get('.delete-button').click({ force: true, multiple: true })
    } else {
      cy.log("No existing routes found...")
    }
  });

或者换一种更直观的方式,判断是否所有按钮都禁用:

cy.get('voyage-suggested-routes')
  .find('button.selectButton')
  .then(($routes) => {
    const allDisabled = $routes.filter(":disabled").length === $routes.length;
    if (allDisabled) {
      cy.log("No existing routes found...")
    } else {
      cy.log("Deleting......")
      cy.get('.delete-button').click({ force: true, multiple: true })
    }
  });

额外注意点

  • 如果你要确保删除按钮和对应的selectButton是关联的,最好不要直接用cy.get('.delete-button')(可能会匹配到其他无关按钮),可以通过$routes的上下文来定位:比如$routes.closest('.route-item').find('.delete-button'),这样更精准。
  • 使用{ force: true }要谨慎,只有当按钮确实存在但被UI遮挡时才用,否则可能会掩盖其他元素定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:27:44