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

如何在Cypress自动化测试中解压已下载的zip文件

Cypress 解压下载目录zip文件实现方案

Cypress浏览器运行环境无本地文件系统操作权限,解压逻辑需要通过运行在Node.js层的自定义Task实现,完整实现步骤如下:

1. 安装依赖

使用轻量无额外依赖的extract-zip库处理zip解压:

npm install extract-zip --save-dev

2. 配置Cypress自定义Task

修改cypress.config.js配置文件,注册解压任务:

const { defineConfig } = require('cypress')
const extract = require('extract-zip')
const path = require('path')
const fs = require('fs')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 注册zip解压任务
      on('task', {
        // 解压指定zip到下载目录
        async unzipDownloadedZip(zipFileName = 'sample.zip') {
          const zipFullPath = path.resolve(config.downloadsFolder, zipFileName)
          // 校验zip文件是否存在
          if (!fs.existsSync(zipFullPath)) {
            return { success: false, error: `zip文件不存在: ${zipFullPath}` }
          }
          try {
            // 直接解压到Cypress默认下载目录
            await extract(zipFullPath, { dir: config.downloadsFolder })
            return { success: true }
          } catch (err) {
            return { success: false, error: err.message }
          }
        },
        // 可选:校验文件是否存在的辅助任务
        async checkFileExists(filePath) {
          return fs.existsSync(path.resolve(config.downloadsFolder, filePath))
        }
      })
      return config
    },
    // 其余原有配置保持不变
  }
})

3. 测试用例中调用

describe('下载文件解压校验', () => {
  it('触发sample.zip下载后完成解压并校验产物', () => {
    // 原有触发下载sample.zip的业务逻辑
    // 示例:cy.get('#download-btn').click()

    // 等待zip文件下载完成,waitUntil来自cypress-wait-until插件,也可替换为固定cy.wait()
    cy.waitUntil(() => cy.task('checkFileExists', 'sample.zip'), {
      timeout: 30000,
      interval: 1000
    })

    // 执行解压
    cy.task('unzipDownloadedZip').its('success').should('eq', true)

    // 校验解压产物,根据实际需要修改校验逻辑
    // 示例:校验解压后的配置文件存在且内容符合预期
    cy.readFile(`${Cypress.config('downloadsFolder')}/config.json`).its('env').should('eq', 'test')
  })
})

注意事项

  • 如果需要自定义解压目录,修改unzipDownloadedZip任务中extract方法的dir参数即可
  • 若需要处理加密zip,可替换extract-zip为adm-zip库,调整解压逻辑即可,无需修改上层调用逻辑

内容的提问来源于stack exchange,提问作者antonio ferreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:05