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

Cypress中结合contains实现if/else判断遇等待问题求助

问题解决:Cypress中使用contains的if/else分支失效

问题原因

你原代码的核心错误是混淆了Cypress的cy.contains()命令和jQuery的方法:

  • $modal是jQuery对象,jQuery并没有$modal.contains('文本')这种用来查找包含指定文本子元素的方法。
  • 当不存在"failure"文本时,$modal.contains('failure')会返回undefined,后续调用.is(':visible')会直接抛出错误,导致代码中断,永远走不到else分支。

解决方案

以下是两种可行的修改方式:

方式一:使用jQuery的:contains选择器

通过jQuery的:contains选择器查找目标元素,先判断元素是否存在,再检查可见性:

cy.get('div[data-testid="upload"]').then($modal => {
  // 查找包含"failure"文本的子元素
  const $failureElement = $modal.find(':contains("failure")');
  // 元素存在且可见时进入if分支,否则进入else
  if ($failureElement.length > 0 && $failureElement.is(':visible')) {
    cy.wait(100000);
  } else {
    cy.wait(200000);
  }
});

方式二:使用Cypress原生DOM检查API

用Cypress提供的Cypress.dom.isVisible方法检查可见性,结合原生数组遍历判断:

cy.get('div[data-testid="upload"]').then($modal => {
  cy.wrap($modal).find('th').then($ths => {
    // 遍历所有<th>元素,检查是否存在文本为"failure"且可见的项
    const hasFailure = Array.from($ths).some(th => {
      return th.textContent.includes('failure') && Cypress.dom.isVisible(th);
    });
    
    if (hasFailure) {
      cy.wait(100000);
    } else {
      cy.wait(200000);
    }
  });
});

关键说明

  • 在Cypress的then回调中操作DOM是同步的,避免了异步命令导致的条件判断失效问题。
  • 优先使用Cypress原生API(如Cypress.dom.isVisible)可以减少jQuery选择器带来的兼容性差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:52:48