配置trashAssetsBeforeRuns:FALSE后,如何让Cypress删除30天前失败截图?
如何通过Cypress自动清理超过1个月的旧截图
Cypress 本身没有内置配置项直接实现自动删除指定时长的旧截图,但你可以通过自定义 Node.js 脚本结合 Cypress 的生命周期钩子来完成这个需求,无需依赖 Jenkins 的额外配置。
实现步骤
- 在 Cypress 配置文件(
cypress.config.js)中添加生命周期钩子,在测试运行前执行清理逻辑 - 编写脚本遍历
cypress/screenshots目录,筛选并删除超过30天的文件/文件夹
代码示例
以下是完整的配置实现,包含递归清理子目录的逻辑(适配Cypress按测试套件分类截图的结构):
const { defineConfig } = require('cypress'); const fs = require('fs').promises; const path = require('path'); // 递归清理旧截图的函数 async function cleanupOldScreenshots(dir) { // 计算30天前的时间戳 const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000; const entries = await fs.readdir(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) { // 递归处理子目录 await cleanupOldScreenshots(fullPath); // 可选:删除清理后为空的子目录 const subDirEntries = await fs.readdir(fullPath); if (subDirEntries.length === 0) { await fs.rmdir(fullPath); console.log(`Removed empty directory: ${fullPath}`); } } else { const stats = await fs.stat(fullPath); // 判断文件修改时间是否超过30天 if (stats.mtime.getTime() < thirtyDaysAgo) { await fs.unlink(fullPath); console.log(`Deleted old screenshot: ${fullPath}`); } } } } module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 在测试运行前执行清理 on('before:run', async () => { const screenshotsRoot = path.join(__dirname, 'cypress', 'screenshots'); try { await cleanupOldScreenshots(screenshotsRoot); } catch (err) { console.error('Failed to clean up old screenshots:', err); } }); }, // 保留历史截图的核心配置 trashAssetsBeforeRuns: false, }, });
说明
- 该脚本会在每次 Cypress 运行前自动执行,清理修改时间超过30天的截图文件
- 递归处理子目录,适配 Cypress 默认的按测试用例/套件分类截图的结构
- 可选逻辑:清理后自动删除空的子目录,保持目录结构整洁
- 完全在 Cypress 配置内实现,无需依赖 Jenkins 插件或额外构建步骤
内容的提问来源于stack exchange,提问作者David Pongo
相关产品推荐
相关产品推荐

