Skip to content

Running Playwright Tests on GitHub Actions: Cache, Sharding and Publishing Reports

  • by

Why a Suite That Passes Locally Collapses on CI

Your Playwright suite runs green on your laptop in four minutes. You push it to GitHub Actions and it takes twenty-two minutes, fails on two tests you can’t reproduce, and the only evidence is a stack trace in the log. Nothing about the tests changed. The machine changed.

A GitHub-hosted runner is a disposable VM: empty file system, no caches, shared CPU with fewer cores than your dev machine, and network latency to whatever environment you test against. Those differences turn into three concrete problems — browser binaries downloaded from scratch on every run, a long suite executing serially on a single runner, and failures you can’t diagnose because nothing was saved before the VM was destroyed. The rest of this post closes those three, in that order.

Minimum Working Workflow: One Job, One Runner

Get a correct baseline green before you optimize anything. If you add caching and sharding to a workflow that was never working, you won’t know which layer broke it.

# .github/workflows/e2e.yml
name: e2e

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright browsers
        run: npx playwright install --with-deps

      - name: Run tests
        run: npx playwright test

      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/
          retention-days: 7

Each step earns its place. checkout puts your code on the empty VM. setup-node pins the Node version so the runner doesn’t silently drift when GitHub updates its images. npm ci installs exactly what package-lock.json says — never npm install on CI, which can resolve different versions. playwright install --with-deps downloads browser binaries and the Linux system libraries they link against, which the runner image does not ship. timeout-minutes kills a hung job instead of burning your quota for six hours. The upload step runs with !cancelled() rather than success() so you get the report precisely when you need it — after a failure.

Dependency Cache: node_modules or the npm Cache

Two different things can be cached, and they are not equivalent.

actions/setup-node with cache: npm caches the npm download cache (~/.npm). On a cache hit, npm ci skips the network but still deletes and rebuilds node_modules by extracting and linking every package. That’s the safe option, and it costs you the linking time.

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - run: npm ci

Caching node_modules directly skips installation entirely:

      - name: Cache node_modules
        id: node-modules
        uses: actions/cache@v4
        with:
          path: node_modules
          key: node-modules-${{ runner.os }}-node20-${{ hashFiles('package-lock.json') }}

      - name: Install dependencies
        if: steps.node-modules.outputs.cache-hit != 'true'
        run: npm ci

Two rules make this safe. The key must contain hashFiles('package-lock.json'), so any lockfile change produces a new key and a fresh install. And do not add restore-keys here — a partial restore gives you a node_modules that doesn’t match your lockfile, which is the stale-dependency failure mode everyone warns about. The OS and Node version belong in the key too, because compiled native modules are built for a specific pair.

The criterion: if npm ci on a warm npm cache takes under ~30 seconds, use cache: npm and stop thinking about it. If your dependency tree is large enough that npm ci costs a minute or more — and that minute is now paid by every shard in parallel — cache node_modules with a strict lockfile key.

Caching Browser Binaries and Keeping Version Alignment

Playwright stores browsers in ~/.cache/ms-playwright. Downloading Chromium, Firefox and WebKit is the single largest fixed cost in a cold Playwright job, and unlike your tests it doesn’t get faster when you shard — every shard pays it.

The cache key must be tied to the Playwright version, not to the lockfile as a whole. If you key on the whole lockfile, you redownload browsers every time an unrelated dependency changes. If you key on something static, you’ll upgrade Playwright one day, restore last version’s binaries, and get Executable doesn't exist at /home/runner/.cache/ms-playwright/chromium-1234/... — a failure that looks like infrastructure and is actually a stale key.

      - name: Resolve Playwright version
        id: pw
        run: |
          VERSION=$(node -p "require('./package-lock.json').packages['node_modules/@playwright/test'].version")
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

      - name: Cache Playwright browsers
        id: pw-cache
        uses: actions/cache@v4
        with:
          path: ~/.cache/ms-playwright
          key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}

      - name: Install browsers and system deps
        if: steps.pw-cache.outputs.cache-hit != 'true'
        run: npx playwright install --with-deps

      - name: Install system deps only
        if: steps.pw-cache.outputs.cache-hit == 'true'
        run: npx playwright install-deps

The second install step is the part people drop. The cache restores browser binaries into the home directory, but --with-deps also installs system packages into /usr/lib via apt — and those are not in the cached path. On a cache hit you still need playwright install-deps, which is cheap and prevents “browser closed unexpectedly during launch” errors that are really missing shared libraries.

If you only test Chromium, add npx playwright install chromium instead of installing all three engines; the cache gets smaller and restores faster.

Splitting Runtime with Sharding: The Matrix Strategy

--shard=i/n splits the test set deterministically: the same suite and same n always produce the same partition, so shard 3 of 5 contains the same tests on every run. Combine it with a GitHub Actions matrix and you get n runners working in parallel.

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    strategy:
      fail-fast: false
      matrix:
        shardIndex: [1, 2, 3, 4]
        shardTotal: [4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      - name: Resolve Playwright version
        id: pw
        run: |
          VERSION=$(node -p "require('./package-lock.json').packages['node_modules/@playwright/test'].version")
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
      - uses: actions/cache@v4
        id: pw-cache
        with:
          path: ~/.cache/ms-playwright
          key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}
      - if: steps.pw-cache.outputs.cache-hit != 'true'
        run: npx playwright install --with-deps
      - if: steps.pw-cache.outputs.cache-hit == 'true'
        run: npx playwright install-deps
      - name: Run shard
        run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}

fail-fast: false is mandatory, not stylistic. The default cancels every other matrix job the moment one fails, so a single failing test in shard 2 destroys the results of shards 1, 3 and 4 and you learn nothing about the rest of the suite.

How many shards? Model the wall clock as S + T/n, where T is total test runtime on one runner and S is the per-job fixed cost — checkout, Node setup, dependency install, cache restore — which is roughly constant regardless of shard count. The marginal saving from going n → n+1 is T / (n·(n+1)). Once that drops below S, you’re adding a full job’s setup cost to buy less time than it costs. In practice the threshold sits around n ≈ T / S: past that point, setup dominates each shard and the curve flattens. A suite with T = 24 minutes and S = 3 minutes flattens around 8 shards, where wall clock is roughly 6 minutes and the ninth shard buys seconds. Lowering S — which is exactly what the browser cache does — is what lets a higher n still pay off.

workers interacts with this. Each shard still runs its slice in parallel within the runner. GitHub-hosted ubuntu-latest runners have 4 cores; workers: 2 in CI is a sane default because browsers are memory-hungry and an oversubscribed runner produces timeouts that look like flakiness. Don’t raise shard count and worker count at the same time — change one, measure, then change the other. The same discipline applies to test automation performance work generally (in Turkish).

What to Do When Shards Are Unbalanced

Playwright shards by test count, not by duration. If one spec file contains a long login-and-checkout journey while the others hold fast unit-ish UI checks, one shard finishes in two minutes and another in eight — and your wall clock is eight. Parallelism bought you nothing beyond the slowest shard.

Three fixes, in order of effort. First, split the heavy spec file into several files so the scheduler has finer-grained units to distribute; a 600-line spec is an optimization barrier as well as a readability problem. Second, if the imbalance comes from a slow project (mobile emulation, WebKit, a separate authenticated suite), give that project its own job with --project= instead of mixing it into the shard pool. Third, when neither applies, read the duration data from the last run’s report and group files manually into named jobs. Manual grouping goes stale, so treat it as the last option, not the first.

Blob Reports and Merging Shards into a Single HTML Report

The moment you shard, each job writes its own HTML report containing a quarter of the truth. Four partial reports is worse than one, because the aggregate pass/fail picture exists nowhere.

The blob reporter solves this. Each shard writes a machine-readable blob, uploads it as an artifact, and a separate job downloads all of them and merges them into one HTML report.

Three blob-reporter shards (1/3, 2/3, 3/3) feed Artifacts blob-report-*, then Merge job (if: always()) to Single HTML report to Publish.

Add to each shard job:

      - name: Run shard
        run: npx playwright test --reporter=blob --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}

      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: blob-report-${{ matrix.shardIndex }}
          path: blob-report/
          retention-days: 1

And the merge job:

  merge-reports:
    if: always()
    needs: [test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci

      - uses: actions/download-artifact@v4
        with:
          path: all-blob-reports
          pattern: blob-report-*
          merge-multiple: true

      - name: Merge into HTML report
        run: npx playwright merge-reports --reporter=html ./all-blob-reports

      - uses: actions/upload-artifact@v4
        with:
          name: html-report
          path: playwright-report/
          retention-days: 14

if: always() on the merge job is the critical line. needs: [test] means the merge job is skipped by default when any shard fails — which is exactly the run you wanted a report for. Without always(), your reporting pipeline works perfectly on green builds and silently produces nothing on red ones.

Two more traps. Artifact names must be unique per shard (hence blob-report-${{ matrix.shardIndex }}), and merge-reports needs the same Playwright version that produced the blobs, which is why the merge job also runs npm ci instead of using a bare npx playwright.

Publishing the Report: Artifacts, GitHub Pages and PR Comments

Three ways to publish a Playwright report: comparing Artifact, GitHub Pages and Job summary across Setup effort, Access speed and Privacy. Artifact: Setup effort Lowest, Access speed Download and unzip and Privacy Repo permissions. GitHub Pages: Setup effort Medium, Access speed One click and Privacy Public on public repos. Job summary: Setup effort Low, Access speed Visible in the run and Privacy Repo permissions.

Artifacts are the default and the safest. The cost is friction: a reviewer must download a zip, unzip it, and open index.html locally. Set retention-days deliberately — the repo default is 90 days, and keeping megabytes of traces and videos for three months across every PR eats storage quota fast. One or two days for blobs, one to two weeks for the merged report.

GitHub Pages turns the report into a link. On a private repo with Pages access restricted to collaborators that’s fine. On a public repo, published Pages content is public to everyone — including your base URLs, screenshots of a staging environment, and any data visible in a trace. Don’t publish reports from a public repo unless you’ve checked what’s inside them.

Job summary writes markdown straight into the run page, visible without any download:

      - name: Write summary
        if: always()
        run: |
          {
            echo "## Playwright results"
            echo ""
            echo "| Run | Commit | Report |"
            echo "| --- | --- | --- |"
            echo "| ${{ github.run_number }} | \`${{ github.sha }}\` | [artifact](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}#artifacts) |"
          } >> "$GITHUB_STEP_SUMMARY"

The practical combination for most teams: blob artifacts for the shards, a merged HTML artifact for debugging, and a job summary that links to it so nobody has to hunt through the Actions UI. Add Pages only when people are actually skipping the download step.

Stability Settings Specific to CI

Branch your config on process.env.CI — GitHub Actions sets it automatically.

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

const isCI = !!process.env.CI;

export default defineConfig({
  testDir: './tests',
  timeout: isCI ? 60_000 : 30_000,
  expect: { timeout: isCI ? 10_000 : 5_000 },
  fullyParallel: true,
  forbidOnly: isCI,
  retries: isCI ? 1 : 0,
  workers: isCI ? 2 : undefined,
  reporter: isCI ? [['blob'], ['github']] : [['html', { open: 'never' }]],
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
    trace: 'on-first-retry',
    video: 'retain-on-failure',
    screenshot: 'only-on-failure',
    actionTimeout: isCI ? 15_000 : 0,
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  ],
});

forbidOnly: isCI fails the build if someone pushes a test.only — otherwise one stray .only turns your suite into a single passing test and nobody notices. Timeouts are higher on CI because a shared-CPU runner genuinely is slower than your machine; a 30-second timeout that’s comfortable locally can be marginal there.

retries: 1 exists to absorb genuine infrastructure noise, not to hide bad tests. Every retry number above 1 is a decision to stop seeing a problem. trace: 'on-first-retry' is the actual diagnostic tool: it records a trace only for tests that failed once, so you pay the cost on exactly the tests you need to inspect, and you open the result with npx playwright show-trace to see the DOM, network and console at each step. That trace is the starting point for finding the root cause of an unstable test (in Turkish).

The github reporter is worth adding on CI: it annotates failures inline on the PR diff.

Managing Secrets, Base URLs and Environment Variables

The environment address and credentials belong in GitHub Secrets and environment variables, not in the repo. The workflow injects them, and playwright.config.ts reads them — BASE_URL for baseURL, and credentials for the setup project that produces storageState:

    env:
      BASE_URL: ${{ vars.BASE_URL }}
      TEST_USER: ${{ secrets.TEST_USER }}
      TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}

Use repository or environment variables (vars) for non-sensitive values like base URLs — they show up in logs, which is convenient, and they’re not secrets to begin with. Use secrets only for credentials. If you need per-environment values (staging vs. production smoke), use GitHub Environments and set environment: staging on the job, which also lets you require approval before a run touches a protected target.

The failure mode nobody plans for: pull requests from forks don’t receive secrets. GitHub deliberately passes empty strings instead, so TEST_PASSWORD becomes '', your login step fails with “invalid credentials”, and the pipeline breaks in a way that looks like an application bug. Handle it explicitly — skip the authenticated suite when github.event.pull_request.head.repo.full_name != github.repository, and either run a credential-free smoke set or gate the full run behind a maintainer-applied label. pull_request_target does give forks access to secrets, and it also runs with write permissions against untrusted code; avoid it for test pipelines.

Sharded, parallel jobs also mean several runners hitting the same environment at once. If your tests share fixture accounts or seeded records, that’s where the cross-shard interference starts — each test should create its own data (in Turkish) rather than rely on a shared state.

Which Trigger Should Run the Pipeline

Running the full suite on every push to every PR is expensive and, past a certain team size, queues jobs behind each other until feedback arrives too late to be feedback. Use three tiers: a tagged smoke subset on pull requests, the full suite on merges to main, and long scenarios on a nightly schedule.

Tag tests at the source:

test('checkout with a saved card @smoke', async ({ page }) => {
  // ...
});

test('order history pagination across 500 records @nightly', async ({ page }) => {
  // ...
});

Then select by event:

on:
  pull_request:
  push:
    branches: [main]
  schedule:
    - cron: '0 2 * * *'

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      - run: npx playwright install --with-deps

      - name: Select scope
        id: scope
        run: |
          case "${{ github.event_name }}" in
            pull_request) echo 'args=--grep @smoke' >> "$GITHUB_OUTPUT" ;;
            schedule)     echo 'args=' >> "$GITHUB_OUTPUT" ;;
            *)            echo 'args=--grep-invert @nightly' >> "$GITHUB_OUTPUT" ;;
          esac

      - name: Run tests
        run: npx playwright test ${{ steps.scope.outputs.args }}

Pull requests run only @smoke. Merges to main run everything except @nightly. The scheduled run takes the whole set. Add concurrency with cancel-in-progress: true keyed on the branch so a second push to the same PR cancels the first run instead of queueing behind it.

What to Do Next

Do these in order, and record the wall-clock time after each step — optimizing without measuring is how people end up with a 90-line workflow that isn’t faster than the 20-line one.

  1. Get the single-job workflow from the second section green. No cache, no matrix. Record the time.
  2. Add the browser binary cache with the version-pinned key. Run twice — the first run is a cache miss and tells you nothing. Record the second time; the difference is your per-job fixed cost S.
  3. Add the dependency cache only if npm ci is still a visible share of S.
  4. Compute T / S from your own numbers and pick a shard count at or below it. Add fail-fast: false. Record the time.
  5. Switch to the blob reporter and add the merge job with if: always(). Verify it by deliberately failing a test and confirming the report still appears.
  6. Publish the merged report and add the job summary link.
  7. Finally, split triggers into smoke / full / nightly once the full pipeline is stable.

If step 4 doesn’t help much, the problem is almost certainly shard imbalance, not shard count — go back and look at the slowest spec file before adding more runners.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.