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

Cypress软断言实现遇错及执行控制异常问题求助

Cypress软断言实现问题:使用cypress-soft-assertions报错且测试终止不符合预期

我用Cypress做自动化测试,想要实现软断言功能——也就是断言失败时,测试不会直接终止,能继续执行后续步骤。尝试使用cypress-soft-assertions包,但遇到了问题,具体情况如下:

操作步骤与问题详情

  1. 安装依赖:执行命令 npm i -D cypress-soft-assertions 安装了该包。
  2. 软断言代码尝试:在测试代码的validateElementVisibility方法里,尝试对元素可见性做软断言(注:代码存在拼写错误,beter应为better):
validateElementVisibility(element, logMsg) {
    this.logger.log(logMsg);
    element.beter('be.visible'); // 拼写错误:正确写法是'better'
}

运行后触发错误:

cy.ensureAttached is not a function
node_modules/cypress-soft-assertions/src/index.js:229:1
  1. 添加异常处理:为阻止测试终止,我在Cypress配置中添加了以下异常处理代码:
Cypress.on("fail", (err, runnable) => {
    console.log(err.message);
    return false;
});

Cypress.on("uncaught:exception", (e, runnable) => {
    console.log("error", e);
    console.log("runnable", runnable);
    console.log("error", e.message);
    return false;
});

Cypress.on('uncaught:exception', (err, runnable) => {
    if (err.message.includes("chai")) {
        cy.log(`Chai Assertion Error: ${err.message}`);
        return false;
    } else {
        throw err;
    }
});

但即便添加了这些代码,断言失败时测试仍会终止,不符合预期。

基础页面代码片段参考

import TestReportLogger from "../../../support/TestReportLogger"

class BasePage {
    constructor() {
        this.logger = new TestReportLogger(); // 原代码中'a'为笔误,修正为new
    }

    // ... 其他方法省略 ...

    validateElementVisibility(element, logMsg) {
        this.logger.log(logMsg);
        element.should('be.visible')
    }

    // 其他方法
}
export default BasePage;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:42:46