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

能否为Playwright不同测试环境分配不同数量的Worker以加速测试?

Playwright不同测试环境分配不同数量的Worker以加速测试?

完全可以做到!你的这个思路非常合理——把staging和production环境的测试拆成两个独立的测试项目,分别分配Worker并行执行,既不会触发单用户会话的限制,又能大幅缩短整体测试时间。下面给你具体的调整步骤:

1. 拆分测试项目配置

你需要把原来按浏览器划分的项目,拆分成「浏览器+环境」的组合,每个环境的项目使用对应的认证存储文件和环境变量。修改你的playwright.config.ts中的projects配置如下:

projects: [
  { 
    name: 'setup', 
    testMatch: /.*\.setup\.ts/,
  },
  // Staging 环境的浏览器项目组
  {
    name: 'chromium-staging',
    use: {
      ...devices['Desktop Chrome'],
      storageState: 'playwright/.auth/staging.json',
      baseURL: process.env.BASEURL,
    },
    dependencies: ['setup'],
    parallelism: 1, // 限制该环境最多用1个Worker
    testMatch: /.*\.staging\.spec.ts/, // 只跑staging相关测试文件
  },
  {
    name: 'firefox-staging',
    use: { 
      ...devices['Desktop Firefox'],
      storageState: 'playwright/.auth/staging.json',
      baseURL: process.env.BASEURL,
    },
    dependencies: ['setup'],
    parallelism: 1,
    testMatch: /.*\.staging\.spec.ts/,
  },
  {
    name: 'webkit-staging',
    use: { 
      ...devices['Desktop Safari'],
      storageState: 'playwright/.auth/staging.json',
      baseURL: process.env.BASEURL,
    },
    dependencies: ['setup'],
    parallelism: 1,
    testMatch: /.*\.staging\.spec.ts/,
  },
  // Production 环境的浏览器项目组
  {
    name: 'chromium-prod',
    use: {
      ...devices['Desktop Chrome'],
      storageState: 'playwright/.auth/prod.json',
      baseURL: process.env.PROD_URL,
    },
    dependencies: ['setup'],
    parallelism: 1,
    testMatch: /.*\.prod\.spec.ts/, // 只跑prod相关测试文件
  },
  {
    name: 'firefox-prod',
    use: { 
      ...devices['Desktop Firefox'],
      storageState: 'playwright/.auth/prod.json',
      baseURL: process.env.PROD_URL,
    },
    dependencies: ['setup'],
    parallelism: 1,
    testMatch: /.*\.prod\.spec.ts/,
  },
  {
    name: 'webkit-prod',
    use: { 
      ...devices['Desktop Safari'],
      storageState: 'playwright/.auth/prod.json',
      baseURL: process.env.PROD_URL,
    },
    dependencies: ['setup'],
    parallelism: 1,
    testMatch: /.*\.prod\.spec.ts/,
  },
],
// 全局设置总Worker数为2,让staging和prod各占一个并行执行
workers: 2,

2. 给测试文件分类

把你的测试文件按环境命名区分:

  • staging环境的测试文件命名为xxx.staging.spec.ts
  • production环境的测试文件命名为xxx.prod.spec.ts

这样上面配置里的testMatch就能自动把测试分配到对应的环境项目中。如果不想改文件名,也可以用测试标签来区分:
比如在staging测试里加:

test.describe.configure({ tag: '@staging' });

然后在项目配置里把testMatch换成:

testMatch: /.*\.spec.ts/,
grep: /@staging/,

prod环境同理用@prod标签。

3. 验证配置逻辑

调整后,Playwright会:

  1. 先执行setup项目,生成两个环境的认证存储文件
  2. 全局启动2个Worker,同时运行一个staging环境的测试和一个prod环境的测试
  3. 每个环境的项目都限制了parallelism:1,不会在同一个环境里并行测试,避免单用户会话冲突

这样既利用了并行测试提速,又完全规避了用户重叠的问题,完美匹配你的需求!

备注:内容来源于stack exchange,提问作者user22068518

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:58:04