如何验证下载文件是否符合指定扩展名而非完整文件名?
解决方案:Cypress下载文件按扩展名断言
问题背景
现有Cypress下载测试仅支持通过完整文件名断言文件是否下载成功,需要扩展为支持通过文件扩展名(如.pdf、.csv)匹配,只要下载目录中存在对应扩展名的文件即判定断言通过。
修改步骤
1. 更新插件逻辑(plugins/index.js)
修改文件检查逻辑,新增扩展名匹配的判断:
**--snip--** const path = require('path'); const fs = require('fs'); const downloadDirectory = path.join(__dirname, '..', 'downloads'); const findDownloadedFile = (target) => { // 判断传入的是扩展名(以.开头)还是完整文件名 if (target.startsWith('.')) { // 遍历下载目录,检查是否有匹配扩展名的文件 if (!fs.existsSync(downloadDirectory)) return false; const files = fs.readdirSync(downloadDirectory); return files.some(file => file.endsWith(target)); } else { // 原有逻辑:检查指定完整文件名是否存在 const filePath = `${downloadDirectory}/${target}`; return fs.existsSync(filePath); } }; const hasFile = (target, ms) => { const delay = 10; return new Promise((resolve, reject) => { if (ms < 0) { const errorMsg = target.startsWith('.') ? `Could not find any file with extension ${target} in ${downloadDirectory}` : `Could not find file ${downloadDirectory}/${target}`; return reject(new Error(errorMsg)); } const found = findDownloadedFile(target); if (found) { return resolve(true); } setTimeout(() => { hasFile(target, ms - delay).then(resolve, reject); }, delay); }); }; **--snip--** // 保留原有任务,同时支持完整文件名和扩展名匹配 on('task', { isExistDownloadedFile(target, ms = 4000) { return hasFile(target, ms); }, }); return config;
2. 修改测试用例
调用任务时传入扩展名即可实现按扩展名断言:
it.only("should download file with specified extension", () => { cy.task('deleteDirectory', downloadsFolder); // 删除下载目录 cy.get("downloadButton").click(); // 下载TEST.pdf文件 cy.task('isExistDownloadedFile', '.pdf').should('equal', true); // 按扩展名断言 cy.task('deleteDirectory', downloadsFolder); // 清理下载目录 });
说明
- 兼容原有逻辑:传入完整文件名时,依然保持原有的精确匹配判断
- 扩展名匹配:传入以
.开头的字符串(如.csv、.txt)时,会遍历下载目录,检查是否存在对应扩展名的文件 - 超时逻辑:保持原有的4秒超时设置,可通过第二个参数自定义超时时间(如
cy.task('isExistDownloadedFile', '.pdf', 6000))
内容的提问来源于stack exchange,提问作者Mag
相关产品推荐
相关产品推荐

