Cypress如何验证文件名为动态值的下载文件是否下载成功
Cypress 下载文件校验两类场景解决方案
Cypress默认下载文件存储路径为cypress/downloads,以下方案均基于该默认路径,如需自定义路径可在cypress.config.js中修改downloadsFolder配置项。
场景1:文件名固定前缀ABC+动态ID的xlsx文件校验
该场景可通过匹配文件名前缀+后缀规则完成校验,操作步骤如下:
- 首先在
cypress.config.js中配置Node层任务,用于操作本地文件系统
// cypress.config.js 完整配置参考 const { defineConfig } = require('cypress') const fs = require('fs/promises') const path = require('path') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on('task', { // 清空指定前缀的旧xlsx下载文件,避免历史文件干扰 clearOldPrefixedFiles(prefix) { const downloadDir = path.join(__dirname, 'cypress/downloads') return fs.readdir(downloadDir) .then(files => { const targetFiles = files.filter(f => f.startsWith(prefix) && f.endsWith('.xlsx')) return Promise.all(targetFiles.map(f => fs.unlink(path.join(downloadDir, f)))) }) .then(() => null) }, // 校验符合前缀规则的文件是否存在,支持自定义正则匹配文件名规则 checkPrefixedFileValid(prefix, nameReg = null) { const downloadDir = path.join(__dirname, 'cypress/downloads') return fs.readdir(downloadDir) .then(files => { return files.some(f => { const matchPrefix = f.startsWith(prefix) && f.endsWith('.xlsx') if (!nameReg) return matchPrefix return matchPrefix && nameReg.test(f) }) }) } }) }, }, })
- 测试用例中调用对应任务完成校验
it('验证ABC前缀的xlsx文件下载成功且文件名符合规则', () => { // 提前清空历史文件 cy.task('clearOldPrefixedFiles', 'ABC') // 触发下载操作,此处替换为实际页面下载触发逻辑 cy.get('[data-testid=download-btn]').click() // 校验文件存在且符合规则,示例规则为前缀ABC+16位小写字母/数字组合+后缀xlsx const nameRule = /^ABC[a-z0-9]{16}\.xlsx$/ cy.task('checkPrefixedFileValid', ['ABC', nameRule], { timeout: 15000 }).should('be.true') })
可根据实际动态ID的规则修改正则表达式,完成更严格的文件名校验。
场景2:完全随机文件名的xlsx文件校验
该场景无固定文件名标识,可通过对比下载前后下载目录内的xlsx文件列表差,判断是否有新增文件完成校验:
- 首先在
cypress.config.js的setupNodeEvents中补充两个任务
on('task', { // 获取当前下载目录下所有xlsx文件列表 getAllXlsxFiles() { const downloadDir = path.join(__dirname, 'cypress/downloads') return fs.readdir(downloadDir).then(files => files.filter(f => f.endsWith('.xlsx'))) }, // 校验是否有新增的xlsx文件 checkNewXlsxExists(oldFileList) { const downloadDir = path.join(__dirname, 'cypress/downloads') return fs.readdir(downloadDir) .then(files => { const currentXlsxFiles = files.filter(f => f.endsWith('.xlsx')) const newFiles = currentXlsxFiles.filter(f => !oldFileList.includes(f)) // 如果需要校验下载数量,可直接返回newFiles.length做判断 return newFiles.length > 0 }) } })
- 测试用例中调用对应任务完成校验
it('验证随机文件名的xlsx文件下载成功', () => { // 记录下载前的xlsx文件列表 cy.task('getAllXlsxFiles').as('oldFileList') // 触发下载操作,此处替换为实际页面下载触发逻辑 cy.get('[data-testid=download-btn]').click() // 对比文件列表判断是否有新增文件 cy.get('@oldFileList').then(oldList => { cy.task('checkNewXlsxExists', oldList, { timeout: 15000 }).should('be.true') }) })
如果测试场景存在同时下载多个文件的需求,可修改任务返回新增文件数量,匹配预期值即可。
内容的提问来源于stack exchange,提问作者Smh
相关产品推荐
相关产品推荐

