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

Cypress中无法选择动态名称PDF文件的解决方法咨询

Cypress动态名称PDF文件作为Fixture的解决方案

问题根源

Cypress的cy.fixture()方法不支持通配符匹配文件,且PDF不在其默认识别的扩展名列表中,直接使用通配符会导致路径解析错误,出现你遇到的找不到文件提示。

解决方案

1. 通过自定义Task动态查找并读取PDF

利用Node.js文件系统模块结合Cypress的cy.task(),实现动态查找指定目录下的PDF文件:

  • 在cypress.config.js中注册自定义Task:

    // cypress.config.js
    const { defineConfig } = require('cypress')
    const fs = require('fs')
    const path = require('path')
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          on('task', {
            getDynamicPdf(folderPath) {
              // 拼接完整的fixtures目录路径
              const fullDirPath = path.join(config.projectRoot, 'cypress', 'fixtures', folderPath)
              // 筛选目录下所有PDF文件
              const pdfFiles = fs.readdirSync(fullDirPath).filter(file => file.endsWith('.pdf'))
              
              if (pdfFiles.length === 0) {
                throw new Error('目标目录下未找到PDF文件')
              }
              // 这里默认取第一个匹配文件,可根据需求调整(比如按修改时间排序取最新)
              const targetFilePath = path.join(fullDirPath, pdfFiles[0])
              // 读取文件为Buffer返回
              return fs.readFileSync(targetFilePath)
            }
          })
        },
      },
    })
    
  • 在测试用例中调用该Task:

    cy.task('getDynamicPdf', 'relative/path/to/pdf/folder').then(pdfBuffer => {
      // 示例:使用文件Buffer执行上传操作(需依赖cypress-file-upload插件)
      cy.get('input[type="file"]').attachFile({
        fileContent: pdfBuffer,
        fileName: 'dynamic-pdf.pdf',
        mimeType: 'application/pdf'
      })
    })
    

2. 已知文件名规则时直接读取

如果能动态生成完整文件名,可直接用cy.readFile()读取(该方法支持任意文件类型):

// 示例:根据时间戳动态生成文件名
const dynamicPdfName = `report-${Date.now()}.pdf`
const fullFilePath = `cypress/fixtures/docs/${dynamicPdfName}`

cy.readFile(fullFilePath, 'binary').then(fileContent => {
  cy.get('input[type="file"]').attachFile({
    fileContent,
    fileName: dynamicPdfName,
    mimeType: 'application/pdf'
  })
})

注意事项

  • 若需上传文件,推荐使用cypress-file-upload插件简化操作
  • 确保PDF文件确实存在于指定的fixtures子目录中,避免路径拼写错误
  • 动态匹配文件时,建议添加额外逻辑(如按文件名前缀、修改时间筛选),确保获取到目标文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:05:21