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

如何解决cy.downloadFile抛出的自签名证书错误?

解决Cypress downloadFile自签名证书错误问题

问题分析

调用cy.task('downloadFile')请求带自签名证书的站点时触发self signed certificate错误,本质是Node.js默认拒绝自签名证书的HTTPS请求,而cypress-downloadfile插件的默认配置未禁用证书验证。

解决方案

方案1:自定义下载任务并禁用证书验证

修改cypress.config.js(或.ts),在setupNodeEvents中替换默认的downloadFile任务,手动添加证书验证禁用配置:

const { defineConfig } = require('cypress')
const https = require('https')
const axios = require('axios')
const fs = require('fs')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async downloadFile(options) {
          const response = await axios({
            url: options.url,
            method: options.method || 'GET',
            responseType: 'stream',
            // 禁用自签名证书验证
            httpsAgent: new https.Agent({ rejectUnauthorized: false })
          })
          
          return new Promise((resolve, reject) => {
            const fileStream = fs.createWriteStream(options.dest)
            response.data.pipe(fileStream)
            fileStream.on('finish', () => resolve())
            fileStream.on('error', (err) => reject(err))
          })
        }
      })
    },
  },
})

测试代码中依然使用return cy.task('downloadFile', { url: '...', dest: '...' })即可。

方案2:全局禁用证书验证(仅临时测试用)

在启动Cypress的命令前添加环境变量,全局跳过Node.js的证书验证:

NODE_TLS_REJECT_UNAUTHORIZED=0 npx cypress run

也可在package.json的scripts里配置:

{
  "scripts": {
    "cy:run": "NODE_TLS_REJECT_UNAUTHORIZED=0 npx cypress run"
  }
}

注意:此方法会降低所有HTTPS请求的安全性,仅适合测试环境临时使用。

方案3:添加自签名证书到信任列表(推荐长期测试用)

将站点的自签名证书导入信任库,或在Cypress配置中指定证书路径:

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        async downloadFile(options) {
          const response = await axios({
            url: options.url,
            method: options.method || 'GET',
            responseType: 'stream',
            httpsAgent: new https.Agent({ 
              ca: fs.readFileSync('./path/to/your/certificate.crt') 
            })
          })
          // 后续文件流处理同方案1
        }
      })
    },
  },
})

该方式既能完成证书验证,又能避免安全风险,适合长期测试环境使用。

内容的提问来源于stack exchange,提问作者Steve McNiven-Scott

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:30:59