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

Cypress操作Material UI表格:元素不存在时未执行else且报错

解决Cypress中Material UI表格记录不存在时无法进入else分支的问题

问题场景与现状

在Material UI表格中,需根据Name列判断某条记录是否存在:

  • 记录存在:执行删除操作
  • 记录不存在:记录“记录不存在”的日志

当前代码问题:

  • 记录存在时,可正常执行删除逻辑
  • 记录不存在时,代码直接报错“该行不存在”,无法进入else分支执行日志记录

原代码

cy.get('.MuiTable-root').first().contains(Program1).then(($el) => {

  if ($el.length > 0) {
    // Element exists, do something
    cy.log(Program1 + ': Program found.')
    cy.get('.MuiTable-root').first().contains('tr', Program1).find('td').first().find('svg.MuiSvgIcon-root').eq(2).click();
    cy.wait(10000)
    cy.get('[title="Save"]').click()
    cy.wait(10000)
    cy.log( Program1 + ': Program deleted.')
  } else {
    // Element does not exist, do something else
    console.log(Program1 + ': Program not found.');
    cy.wait(3000)
    cy.log( Program1 + ': Program not found.')
  }
  cy.wait(5000)
  cy.get('.lw-header__logout > img').click();
  cy.wait(5000)
})

问题原因

Cypress的cy.contains()命令默认会等待并断言目标元素存在,如果元素不存在,该命令会直接抛出错误终止流程,根本无法进入后续的.then()回调,因此else分支永远不会被执行。

解决方案

方案1:使用jQuery DOM查询(推荐)

先获取表格元素,再用jQuery的方式在表格内部查找目标记录,这种方式不会触发Cypress的存在断言,即使元素不存在也能正常进入判断逻辑:

cy.get('.MuiTable-root').first().then(($table) => {
  // 在当前表格范围内查找目标记录
  const $targetRow = $table.find(`tr:contains("${Program1}")`);

  if ($targetRow.length > 0) {
    cy.log(`${Program1}: Program found.`)
    // 直接从已找到的行中操作删除按钮
    $targetRow.find('td').first().find('svg.MuiSvgIcon-root').eq(2).click();
    // 替换硬等待为断言等待(更可靠)
    cy.get('[title="Save"]').should('be.visible').click()
    cy.log(`${Program1}: Program deleted.`)
  } else {
    console.log(`${Program1}: Program not found.`);
    cy.log(`${Program1}: Program not found.`)
  }

  cy.wait(5000)
  cy.get('.lw-header__logout > img').click();
})

方案2:捕获命令失败异常

利用Cypress命令的Promise特性,通过.catch()捕获元素不存在的错误,进入异常处理分支:

cy.get('.MuiTable-root').first().then(($table) => {
  cy.wrap($table).contains('tr', Program1)
    .then(($targetRow) => {
      // 记录存在时的逻辑
      cy.log(`${Program1}: Program found.`)
      $targetRow.find('td').first().find('svg.MuiSvgIcon-root').eq(2).click();
      cy.get('[title="Save"]').should('be.visible').click()
      cy.log(`${Program1}: Program deleted.`)
    })
    .catch(() => {
      // 记录不存在时的逻辑
      console.log(`${Program1}: Program not found.`);
      cy.log(`${Program1}: Program not found.`)
    })
    .finally(() => {
      // 无论记录是否存在都执行退出操作
      cy.wait(5000)
      cy.get('.lw-header__logout > img').click();
    })
})

注意事项

  • 尽量避免使用硬编码的cy.wait(10000),改用should('be.visible')或其他断言等待元素状态,提升用例的稳定性。
  • 操作DOM元素时,尽量基于已获取的父元素(如$table、$targetRow)进行查找,减少全局查找带来的不确定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:02:11