跳至主要內容

分片

預設情況下,WebdriverIO 會並行執行測試,並力求最佳化您機器上的 CPU 核心利用率。為了實現更大的平行化,您可以透過在多台機器上同時執行測試來進一步擴展 WebdriverIO 測試執行。我們將這種操作模式稱為「分片」。

在多台機器之間分片測試

若要對測試套件進行分片,請將 --shard=x/y 傳遞至命令列。例如,若要將套件分割成四個分片,每個分片執行四分之一的測試

npx wdio run wdio.conf.js --shard=1/4
npx wdio run wdio.conf.js --shard=2/4
npx wdio run wdio.conf.js --shard=3/4
npx wdio run wdio.conf.js --shard=4/4

現在,如果您在不同的電腦上並行執行這些分片,您的測試套件將快四倍完成。

GitHub Actions 範例

GitHub Actions 支援使用 在多個工作之間分片測試,使用 jobs.<job_id>.strategy.matrix 選項。matrix 選項將為提供的每個選項組合執行一個獨立的工作。

下列範例將示範如何設定工作以在四台機器上並行執行測試。您可以在 Cucumber Boilerplate 專案中找到整個管道設定。

  • 首先,我們將 matrix 選項新增至我們的工作設定,其中 shard 選項包含我們要建立的分片數量。shard: [1, 2, 3, 4] 將建立四個分片,每個分片都有不同的分片編號。
  • 然後,我們使用 --shard ${{ matrix.shard }}/${{ strategy.job-total }} 選項執行我們的 WebdriverIO 測試。這將是每個分片的測試命令。
  • 最後,我們將 wdio 記錄報告上傳至 GitHub Actions Artifacts。這將在分片失敗時提供記錄。

測試管道定義如下

name: Test

on: [push, pull_request]

jobs:
lint:
# ...
unit:
# ...
e2e:
name: 🧪 Test (${{ matrix.shard }}/${{ strategy.job-total }})
runs-on: ubuntu-latest
needs: [lint, unit]
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v4
- uses: ./.github/workflows/actions/setup
- name: E2E Test
run: npm run test:features -- --shard ${{ matrix.shard }}/${{ strategy.job-total }}
- uses: actions/upload-artifact@v1
if: failure()
with:
name: logs-${{ matrix.shard }}
path: logs

這將並行執行所有分片,將測試的執行時間減少 4 倍

GitHub Actions example

請參閱 96d444e 的提交,來自 Cucumber Boilerplate 專案,該專案將分片引入其測試管道,這有助於將整體執行時間從 2:23 分鐘 減少到 1:30 分鐘,減少了 37% 🎉。

歡迎!我能如何幫您?

WebdriverIO AI Copilot