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

如何用Playwright验证Zip压缩包内文件的格式?(JavaScript)

用Playwright(JavaScript)自动化验证下载的Zip压缩包内部文件格式

核心思路

通过Playwright捕获下载的Zip文件,借助Node.js的解压库(如adm-zip)解压文件,最后遍历或读取内部文件验证格式,完成后清理临时文件。


步骤1:准备依赖

先安装解压所需的adm-zip库:

npm install adm-zip --save-dev

步骤2:完整代码实现

const { test, expect } = require('@playwright/test');
const AdmZip = require('adm-zip');
const fs = require('fs/promises');
const path = require('path');
const os = require('os');

test('验证下载Zip包的内部文件格式', async ({ page }) => {
  // 创建临时下载目录,避免文件冲突
  const downloadDir = await fs.mkdtemp(path.join(os.tmpdir(), 'playwright-download-'));
  
  // 配置Playwright的下载行为
  await page.context().setDownloadBehavior({
    path: downloadDir,
    acceptDownloads: true
  });

  // 触发下载动作(替换成你的下载按钮选择器/操作逻辑)
  await page.click('#download-zip-btn');

  // 等待下载完成并获取文件路径
  const download = await page.waitForEvent('download');
  const downloadedZipPath = await download.path();
  
  // 基础校验:文件存在且为Zip格式
  expect(await fs.access(downloadedZipPath)).resolves.not.toThrow();
  expect(downloadedZipPath.endsWith('.zip')).toBe(true);

  // 初始化Zip对象并解压到临时目录
  const zip = new AdmZip(downloadedZipPath);
  const extractDir = await fs.mkdtemp(path.join(os.tmpdir(), 'playwright-extract-'));
  zip.extractAllTo(extractDir, true); // true表示覆盖已有文件

  // --------------------------
  // 这里替换成你的验证逻辑
  // --------------------------
  // 示例1:校验所有文件都是CSV格式
  const extractedFiles = await fs.readdir(extractDir, { withFileTypes: true });
  for (const file of extractedFiles) {
    if (!file.isDirectory()) {
      const fileExt = path.extname(file.name).toLowerCase();
      expect(fileExt).toBe('.csv');
    }
  }

  // 示例2:校验某个特定文件是合法JSON
  // const jsonFile = path.join(extractDir, 'metadata.json');
  // const jsonContent = await fs.readFile(jsonFile, 'utf8');
  // expect(() => JSON.parse(jsonContent)).not.toThrow();

  // 清理临时文件,避免残留
  await fs.rm(downloadDir, { recursive: true, force: true });
  await fs.rm(extractDir, { recursive: true, force: true });
});

关键细节说明

  • 临时目录用os.tmpdir()配合mkdtemp生成,避免多测试用例冲突
  • 下载完成后必须用await download.path()获取真实文件路径,不能直接用download.suggestedFilename()
  • 验证逻辑可灵活调整:比如检查文件大小、特定内容片段、文件数量等
  • 若需要处理大型Zip包,可改用unzipper库实现流式解压,避免内存占用过高

内容的提问来源于stack exchange,提问作者Krishna H V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:52:12