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

Cypress Mochawesome截图转Base64嵌入HTML报告邮件发送求助

Cypress + Mochawesome 嵌入Base64截图到HTML报告适配邮件发送

核心问题排查与修复

你当前代码的主要问题集中在路径拼接的可靠性和addContext的使用方式上,以下是针对Cypress环境的专用实现方案:

步骤1:配置依赖与基础设置

首先确保安装适配的报告器:

npm install cypress-mochawesome-reporter --save-dev

修改cypress.config.js,启用报告器并开启内嵌资源(适配邮件需求):

const { defineConfig } = require('cypress');

module.exports = defineConfig({
  reporter: 'cypress-mochawesome-reporter',
  reporterOptions: {
    inlineAssets: true, // 强制将所有资源嵌入HTML(包括图片)
    reportPageTitle: '自动化测试报告',
    embeddedScreenshots: false, // 关闭默认截图嵌入,改用自定义Base64逻辑
  },
  e2e: {
    setupNodeEvents(on, config) {
      require('cypress-mochawesome-reporter/plugin')(on);
    },
  },
});

步骤2:自定义截图转Base64并嵌入报告

替换你当前的test:after:run事件代码,优化路径处理和错误捕获:

const fs = require('fs');
const path = require('path');

Cypress.on('test:after:run', (test, runnable) => {
  // 仅处理最终重试后仍失败的用例
  if (test.state === 'failed' && test.currentRetry === test.retries) {
    // 遍历用例层级,构建符合Cypress默认命名的路径
    const testHierarchy = [];
    let currentRunnable = runnable;
    while (currentRunnable.parent) {
      // 清理特殊字符,避免路径解析错误
      testHierarchy.unshift(currentRunnable.title.replace(/[^\w\s-]/g, ''));
      currentRunnable = currentRunnable.parent;
    }
    testHierarchy.push(path.basename(Cypress.spec.name, '.js'));

    // 生成截图文件名
    let screenshotName = `${testHierarchy.join(' -- ')} -- ${test.title.replace(/[^\w\s-]/g, '')} (failed).png`;
    // 处理重试后的文件名后缀
    if (test.retries > 0) {
      screenshotName = screenshotName.replace('(failed)', '(failed) (attempt 2)');
    }

    // 构建完整截图路径
    const fullPath = path.join(Cypress.config('screenshotsFolder'), screenshotName);

    try {
      // 读取文件并转换为Base64
      const base64Str = fs.readFileSync(fullPath, 'base64');
      // 导入addContext并添加到报告上下文
      const addContext = require('mochawesome/addContext');
      addContext({ test }, {
        title: '失败截图',
        value: `data:image/png;base64,${base64Str}`
      });
    } catch (err) {
      console.error('读取或转换截图失败:', err.message);
    }
  }
});

关键说明

  1. 路径处理:使用path.join保证跨平台兼容性,遍历runnable层级生成和Cypress默认截图一致的文件名,避免路径找不到的问题。
  2. 环境适配:test:after:run属于Node.js环境,不能使用Cypress的cy.readFile命令,必须用Node原生的fs.readFileSync。
  3. 错误捕获:添加try-catch块,方便调试文件读取失败的场景(比如截图未生成、路径错误)。
  4. 邮件适配:开启inlineAssets后,Mochawesome会将Base64图片直接嵌入HTML,发送邮件时无需附加图片文件,收件方可直接查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 06:23:12