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

Cypress cy.origin中软断言异常:断言失败但测试仍通过

问题原因

cy.origin的回调函数运行在完全独立的沙盒执行上下文中,和外层it测试块的上下文相互隔离。

常规软断言的实现通常会在一个全局(或外层上下文维护的)数组中收集断言失败信息,最后在测试结束时检查该数组并抛出错误。但cy.origin内部无法访问外层上下文的这个错误集合,导致内部的软断言失败信息无法被外层测试逻辑捕获,因此测试用例会错误地显示通过。

解决方法

核心思路是将cy.origin内部收集到的软断言失败信息传递回外层上下文,合并到全局错误集合中,最终统一触发测试失败。

步骤1:改造软断言模块

在你的soft_assertions.js中添加获取、重置错误集合的方法,方便在不同上下文中传递错误:

let softErrors = [];

chai.use(function(chai, utils) {
  chai.softExpect = function(actual) {
    return new chai.Assertion(actual).then(
      () => {}, // 断言成功时无操作
      (failInfo) => {
        softErrors.push(failInfo);
      }
    );
  };

  // 新增:获取当前错误列表的副本
  chai.getSoftErrors = () => [...softErrors];
  // 新增:重置错误列表
  chai.resetSoftErrors = () => { softErrors = []; };
});

步骤2:调整测试用例逻辑

在测试用例中,从cy.origin回调返回内部的错误列表,外层通过.then接收并合并到全局错误集合,最后在测试结束时统一检查:

describe('dummy test', () => {
  // 每次测试前重置错误集合
  beforeEach(() => {
    chai.resetSoftErrors();
  });

  // 测试结束后检查所有软断言错误
  afterEach(() => {
    const allErrors = chai.getSoftErrors();
    if (allErrors.length > 0) {
      const errorMessages = allErrors.map(err => err.message).join('\n');
      throw new Error(`软断言失败:\n${errorMessages}`);
    }
  });

  it('tests with cy.origin - now fails correctly', () => {
    cy.origin('some.url', () => {
      // 在cy.origin上下文重新引入软断言模块
      Cypress.require('../../support/modules/soft_assertions.js');
      // 执行软断言
      chai.softExpect(1).to.equal(3);
      // 返回当前上下文的错误列表
      return chai.getSoftErrors();
    }).then(originErrors => {
      // 将cy.origin内的错误合并到全局错误集合
      const globalErrors = chai.getSoftErrors();
      globalErrors.push(...originErrors);
    });

    // 外层的软断言可以正常使用
    // chai.softExpect('foo').to.equal('bar');
  });
});

关键说明

  • cy.origin内部的chai实例和外层的是独立的,因此必须在回调内重新引入软断言模块。
  • 通过return将内部错误列表传递到外层,再合并到全局集合,确保所有软断言失败都能被最终检查到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:31:24