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

如何在Cypress中重命名已下载的文件?

在Cypress测试中重命名已下载文件的方法

可以通过Cypress的cy.task调用Node.js的文件系统模块实现,步骤如下:

1. 配置下载目录(可选)

先确认Cypress配置文件(cypress.config.js)中的下载路径,默认是cypress/downloads,也可自定义:

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

module.exports = defineConfig({
  e2e: {
    downloadsFolder: 'cypress/downloads',
    // 其他配置项...
  },
});

2. 注册重命名文件的Task

在cypress.config.js的setupNodeEvents中注册task,处理文件重命名逻辑:

setupNodeEvents(on, config) {
  on('task', {
    renameDownloadedFile: ({ originalName, newName, downloadsFolder }) => {
      const fs = require('fs');
      const path = require('path');
      const originalPath = path.join(downloadsFolder, originalName);
      const newPath = path.join(downloadsFolder, newName);

      if (fs.existsSync(originalPath)) {
        fs.renameSync(originalPath, newPath);
        return true;
      }
      return false;
    }
  });
  return config;
}

如果下载文件名是动态生成的(带时间戳、随机串等),可以修改task匹配文件名:

renameDownloadedFile: ({ filePattern, newName, downloadsFolder }) => {
  const fs = require('fs');
  const path = require('path');
  const files = fs.readdirSync(downloadsFolder);
  // 匹配包含指定关键词的文件,可按需调整规则
  const targetFile = files.find(file => file.includes(filePattern));
  
  if (targetFile) {
    const originalPath = path.join(downloadsFolder, targetFile);
    const newPath = path.join(downloadsFolder, newName);
    fs.renameSync(originalPath, newPath);
    return true;
  }
  return false;
}

3. 在测试中调用重命名Task

下载完成并验证后,调用注册好的task完成重命名:

cy.get(':nth-child(2) > .btn').contains(domData.dwnldContractFiles)
  .as('dwnldContractFiles')
  .should('exist').should('be.visible').and('not.be.disabled')

cy.get('@dwnldContractFiles').click()

// 先验证文件下载完成
cy.verifyDownload(domData.allFiles, {timeout: 30000, interval: 3000})

// 固定文件名场景调用
cy.task('renameDownloadedFile', {
  originalName: domData.allFiles,
  newName: 'your-new-filename.pdf',
  downloadsFolder: Cypress.config('downloadsFolder')
}).then((success) => {
  success ? cy.log('文件重命名成功') : cy.log('原文件不存在,重命名失败');
})

// 动态文件名场景调用示例
// cy.task('renameDownloadedFile', {
//   filePattern: 'contract', // 替换为文件关键词
//   newName: 'renamed-contract.pdf',
//   downloadsFolder: Cypress.config('downloadsFolder')
// })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:40:29