如何在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
相关产品推荐
相关产品推荐

