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

Cypress满足特定条件时测试失败、保留cy.log并输出自定义报错

Cypress 自定义报错及日志前置执行解决方案

问题根因

Cypress 所有cy.开头的命令都是异步入队执行的,你原写法中同步获取工具函数返回值做断言时,工具函数内的cy.log还没实际运行,断言直接失败就终止了测试流程,因此日志无法正常输出。

实现方案

将断言和错误抛出逻辑放在工具函数内部,保证日志命令先执行完成后再抛出自定义错误,修改代码如下:

1. 调整utils.js方法

/**
 * 校验对象数组中是否所有元素都匹配给定关键词
 * @param {*} list 待校验对象数组
 * @param {*} searchKeyword 搜索关键词
 */
export const verifyMatchedItems = (list, searchKeyword) => {
  const matchedItems = {
    title: [],
    region: [],
    country: [],
  };

  const nonMatchedItems = [];

  // 原map仅做遍历无返回值,优化为forEach更符合语义
  list.forEach((item) => {
    if (item.title.includes(searchKeyword)) {
      matchedItems.title.push(item.title);
    } else if (item.region.includes(searchKeyword)) {
      matchedItems.region.push(item.region);
    } else if (item.country.includes(searchKeyword)) {
      matchedItems.country.push(item.country);
    } else {
      nonMatchedItems.push(item);
    }
  });

  // 按队列顺序先执行日志打印
  cy.log("Matched-Items:" + JSON.stringify(matchedItems));

  if (nonMatchedItems.length > 0) {
    cy.log("nonMatchedItems:" + JSON.stringify(nonMatchedItems));
    // 日志输出完成后抛出自定义错误
    throw new Error("Failed to due bla bla bla... 不匹配条目数量:" + nonMatchedItems.length);
  }
};

2. 调整测试用例调用逻辑

无需再获取返回值做额外断言,直接调用方法即可:

// 获取搜索结果页所有数据并存储
cy.getResultList().then((searchResultDetails) => {
  // 校验关键词是否匹配结果属性
  Utils.verifyMatchedItems(searchResultDetails, searchKeyword);
});

修改后执行测试时,会先输出匹配/不匹配条目的日志,存在不匹配条目时会直接抛出自定义错误信息,同时测试失败报告也会完整展示所有前置日志内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:27:01