如何在Cypress中校验名称未知的下载文件是否存在
Cypress 未知文件名PDF下载校验方案
你可以通过对比下载前后下载目录内的PDF文件列表,识别出新增的下载文件完成校验,具体操作如下:
前置配置
首先需要在Cypress的Node层配置自定义task,用于获取指定目录下的所有PDF文件名(浏览器端无法直接操作本地文件系统,需通过Node层task实现):
const { defineConfig } = require('cypress') const fs = require('fs/promises') const path = require('path') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on('task', { // 入参为目标文件夹路径,返回该目录下所有PDF文件名数组 getPdfFilesInDir(dirPath) { return fs.readdir(dirPath) .then(files => files.filter(file => path.extname(file).toLowerCase() === '.pdf')) } }) }, } })
测试用例编写
在测试代码中按下载前记录基准列表、执行下载、下载后对比列表的逻辑编写:
const downloadsFolder = Cypress.config('downloadsFolder') let beforeDownloadPdfList = [] // 第一步:获取下载前目录内已有的PDF列表作为基准 cy.task('getPdfFilesInDir', downloadsFolder).then(pdfList => { beforeDownloadPdfList = pdfList }) // 第二步:执行触发下载的操作,替换为你实际的按钮选择器 cy.get('#download-pdf-btn').click() // 第三步:轮询等待下载完成,校验新增PDF存在 cy.task('getPdfFilesInDir', downloadsFolder, { timeout: 10000 }) .should(afterDownloadPdfList => { // 过滤出新增的PDF文件 const newPdfList = afterDownloadPdfList.filter(file => !beforeDownloadPdfList.includes(file)) // 校验有且仅有1个新增PDF,可根据你的业务场景调整判断规则 expect(newPdfList).to.have.lengthOf(1) // 可选:如果需要进一步校验文件存在/内容,读取新增的PDF const newPdfPath = path.join(downloadsFolder, newPdfList[0]) cy.readFile(newPdfPath).should('exist') })
适配调整说明
- 如果业务场景允许单次触发下载多个PDF,调整
expect(newPdfList).to.have.lengthOf(1)的判断规则匹配预期即可 - 大文件下载场景可适当增大
timeout参数值,避免文件未下载完成就触发校验失败 - 如果需要排除浏览器下载过程中的临时文件(如Chrome的
.crdownload后缀文件),可在getPdfFilesInDir的过滤逻辑中额外排除临时文件后缀
内容的提问来源于stack exchange,提问作者Paul Eng
相关产品推荐
相关产品推荐

