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

如何在Cypress中检查下载文件夹并删除已存在的目标文件

在Cypress中实现下载前删除旧Excel文件的方案

错误原因

你直接在Cypress测试代码中调用Node.js的fs模块方法报错,是因为Cypress的测试逻辑运行在浏览器上下文中,无法直接访问Node.js的原生API(比如fs.readdirSync、fs.unlinkSync)。

正确实现步骤

1. 在Cypress配置文件中注册自定义Task

Task是Cypress提供的在Node.js环境中执行代码的机制,可通过它安全操作文件系统。

修改cypress.config.js(旧版本对应cypress/plugins/index.js),添加如下代码:

const { defineConfig } = require("cypress");
const fs = require('fs');
const path = require('path');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 注册删除指定文件的task
      on('task', {
        deleteTargetFile(fileName) {
          const downloadsPath = path.join(__dirname, 'downloads');
          const targetFilePath = path.join(downloadsPath, fileName);
          
          if (fs.existsSync(targetFilePath)) {
            fs.unlinkSync(targetFilePath);
            return `已删除旧文件: ${targetFilePath}`;
          }
          return `未找到目标文件: ${targetFilePath}`;
        }
      });
    },
  },
});

2. 在测试用例中调用Task并执行下载

在测试代码里先调用自定义Task删除旧文件,再执行下载操作:

// 下载前删除旧的someData.xlsx文件
cy.task('deleteTargetFile', 'someData.xlsx').then(cy.log);

// 执行下载操作(示例:点击下载按钮,需替换为你的实际选择器)
cy.get('#download-excel-btn').click();

// 验证新文件成功下载
cy.readFile('downloads/someData.xlsx', 'binary').should('exist');

扩展:清空整个下载文件夹

如果需要删除下载文件夹内所有文件而非单个文件,可修改Task为:

on('task', {
  clearDownloadsFolder() {
    const downloadsPath = path.join(__dirname, 'downloads');
    if (fs.existsSync(downloadsPath)) {
      fs.readdirSync(downloadsPath).forEach(file => {
        fs.unlinkSync(path.join(downloadsPath, file));
      });
      return '已清空下载文件夹';
    }
    return '下载文件夹不存在';
  }
});

测试中调用方式:

cy.task('clearDownloadsFolder').then(cy.log);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:05:19