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

如何在Cypress测试中使用jsonAssertion.softAssert断言元素可见

如何在Cypress中实现元素可见性的软断言

我来帮你搞定这个问题!核心原因在于你当前的softAssert命令是基于json-soft-assert库的值对比逻辑,而元素可见性是Cypress基于DOM状态的断言(依赖Chai-jQuery的判断逻辑),不是简单的“值相等”场景,所以直接用现有softAssert无法适配。

下面是具体的解决方案,我们可以扩展自定义命令来支持可见性的软断言:

步骤1:扩展自定义命令

修改你的自定义命令代码,新增一个专门处理元素可见性的softAssertVisible命令:

const jsonAssertion = require("soft-assert")

Cypress.Commands.add('softAssert', (actual, expected, message) => {
  jsonAssertion.softAssert(actual, expected, message)
  if (jsonAssertion.jsonDiffArray.length) {
    jsonAssertion.jsonDiffArray.forEach(diff => {
      Cypress.log({
        name: 'Soft assertion error',
        displayName: 'softAssert',
        message: diff.error.message
      })
    })
  }
});

Cypress.Commands.add('softContains', (actual, expected, message) => {
  jsonAssertion.softContains(actual, expected, message)
  if (jsonAssertion.jsonDiffArray.length) {
    jsonAssertion.jsonDiffArray.forEach(diff => {
      Cypress.log({
        name: 'Soft assertion error',
        displayName: 'softContains',
        message: diff.error.message
      })
    })
  }
});

// 新增:元素可见性软断言命令
Cypress.Commands.add('softAssertVisible', (selector, customMessage) => {
  cy.get(selector).then($element => {
    // 获取元素的可见状态(用jQuery的is方法判断)
    const isElementVisible = $element.is(':visible');
    // 用softAssert断言状态为true
    const defaultMessage = `Expected element "${selector}" to be visible`;
    jsonAssertion.softAssert(isElementVisible, true, customMessage || defaultMessage);
    
    // 输出错误日志(和现有命令逻辑保持一致)
    if (jsonAssertion.jsonDiffArray.length) {
      jsonAssertion.jsonDiffArray.forEach(diff => {
        Cypress.log({
          name: 'Soft assertion error',
          displayName: 'softAssertVisible',
          message: diff.error.message
        })
      })
    }
  })
});

Cypress.Commands.add('softAssertAll', () => jsonAssertion.softAssertAll())

步骤2:在测试中使用新命令

现在你可以用softAssertVisible替代原来的.should('be.visible'),并且必须在测试末尾调用softAssertAll(),否则软断言的错误不会被抛出:

describe('Load Validation Test', function(){
  it('Load Validation Test', function(){
    // 对输入框做可见性软断言
    cy.softAssertVisible('input[placeholder="Activity Name"]', '活动名称输入框应该可见');
    // 对表格做可见性软断言
    cy.softAssertVisible('div table[class="table table-striped b-t b-light table-nowrap"]', '数据表格应该可见');
    // 对按钮做可见性软断言(示例)
    cy.softAssertVisible('button[type="submit"]', '提交按钮应该可见');

    // 关键:必须调用此方法,否则所有软断言的错误不会触发测试失败
    cy.softAssertAll();
  })
})

方案原理说明

  • 先通过cy.get(selector)获取目标元素(Cypress会自动重试直到元素被找到,和原生断言逻辑一致)
  • 用jQuery的is(':visible')方法获取元素的真实可见状态,将其作为actual值传入softAssert
  • 对比该状态是否为true,完美适配软断言的逻辑,同时保留了Cypress查找元素的重试机制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:19:07