All Guides
aiplaywrightbrowsernetwork-mockingregression-testingdebugging

Turn a browser retry bug into a network regression fixture

Build a deterministic Playwright reproduction for a failed shipping quote, prove the bug, and verify the repair without a live API.

Ryan VerWey
2026-11-05
6 min read

A customer reports that retrying a failed shipping quote adds the shipping charge twice. A screenshot proves the symptom; a network fixture makes the failure repeatable. Give a coding agent the smallest observable contract, a synthetic API response sequence, and assertions that distinguish a working repair from a test that simply stopped exercising the retry.

This guide builds a small Playwright example that runs without a server or shipping-provider account. It tests browser behavior under controlled responses. A separate integration check must establish that those responses still match the real API.

Start with the behavior and inputs

Write the contract before changing code:

  • Items cost 12,500 cents. A successful quote replaces the shipping amount with 500 cents; it never accumulates it.
  • The first quote returns HTTP 503. The UI explains that shipping is unavailable, preserves the items total, and enables an explicit retry.
  • The second quote succeeds. The UI displays a total of 13,000 cents and makes exactly two quote requests overall.
  • A later successful refresh of the same quote still produces 13,000 cents, not 13,500.

Collect the affected route, user action, expected result, observed result, relevant status codes, and the smallest sanitized response bodies. Record browser/project versions, locale, feature flags, and the API contract version when they matter. Use synthetic data; a customer HAR can contain cookies, authorization headers, and personal data. Do not commit an unreviewed recording.

Run this worked fixture

Use a disposable folder or an existing Playwright project. For a new folder, install Playwright Test, install its Chromium browser, and keep the generated lockfile with any reusable fixture. Run locally; no hosted CI service is required.

npm init -y
npm install --save-dev @playwright/test
npx playwright install chromium

Save this as shipping.spec.cjs. The HTML below is a deliberately small demonstration application. In a real repository, navigate to the actual checkout route and keep its UI code outside the test; replacing the app with this demonstration would test the example rather than your repair.

const { test, expect } = require('@playwright/test');

const shell = `<!doctype html><html lang="en"><body>
  <h1>Shipping quote</h1>
  <button type="button">Check shipping</button>
  <p role="status" aria-label="Quote status">Ready</p>
  <p>Total cents: <output>12500</output></p>
  <script>
    const button = document.querySelector('button');
    const status = document.querySelector('[role="status"]');
    const total = document.querySelector('output');
    let shipping = 0;
    button.onclick = async () => {
      button.disabled = true;
      status.textContent = 'Checking';
      try {
        const response = await fetch('/api/shipping-quote');
        if (!response.ok) throw new Error('Quote unavailable');
        const quote = await response.json();
        if (!Number.isSafeInteger(quote.shippingCents) || quote.shippingCents < 0) {
          throw new Error('Invalid quote');
        }
        shipping = quote.shippingCents;
        total.textContent = String(12500 + shipping);
        status.textContent = 'Quote ready';
      } catch {
        status.textContent = 'Shipping unavailable. Retry.';
      } finally {
        button.disabled = false;
      }
    };
  </script>
</body></html>`;

test('a failed quote can be retried without accumulating shipping', async ({ page }) => {
  let quoteRequests = 0;
  await page.route('https://checkout.test/', route => route.fulfill({
    contentType: 'text/html', body: shell
  }));
  await page.route('https://checkout.test/api/shipping-quote', async route => {
    quoteRequests += 1;
    await route.fulfill({
      status: quoteRequests === 1 ? 503 : 200,
      contentType: 'application/json',
      body: JSON.stringify(quoteRequests === 1
        ? { error: 'temporary_unavailable' }
        : { shippingCents: 500 })
    });
  });
  await page.goto('https://checkout.test/');
  const button = page.getByRole('button', { name: 'Check shipping' });
  const status = page.getByRole('status', { name: 'Quote status' });
  const total = page.locator('output');

  await button.click();
  await expect(status).toHaveText('Shipping unavailable. Retry.');
  await expect(button).toBeEnabled();
  await expect(total).toHaveText('12500');

  await button.click();
  await expect(status).toHaveText('Quote ready');
  await expect(total).toHaveText('13000');
  expect(quoteRequests).toBe(2);

  await button.click();
  await expect(status).toHaveText('Quote ready');
  await expect(total).toHaveText('13000');
  expect(quoteRequests).toBe(3);
});
npx playwright test shipping.spec.cjs --workers=1 --repeat-each=5 --trace=retain-on-failure

The explicit retry covers recovery; the third request exposes accumulation. To prove the fixture detects that bug, temporarily change shipping = quote.shippingCents to shipping += quote.shippingCents. The test must fail on the final total with 13,500 instead of 13,000. Restore the assignment and rerun. If the broken variant passes, the fixture is not ready to guard the repair.

Adapt it to the actual application

Keep the response sequence and user-visible assertions; replace the synthetic shell with the real route. Match the exact request method, path, and required payload. A fixture that accepts any request body can hide an application that sends the wrong address or currency.

Install network routes before navigation or the triggering action. Prefer role/name locators and Playwright's retrying assertions over fixed sleeps. Give each test a fresh context and reset the response counter per test. If service workers intercept the request, follow Playwright's network guidance and use serviceWorkers: 'block' for that controlled fixture project, then test the real service-worker behavior separately.

Add cases deliberately: an invalid successful payload, a terminal business rejection, and a transport failure are different from HTTP 503. Model only the scenarios the app contract supports. A HAR replay is useful when many endpoints matter, but inspect and sanitize it, freeze its matching rules, and fail unexpected requests instead of silently falling through to the live service.

Give the agent a bounded repair brief

Copy and fill this brief:

Problem: Retry/refresh accumulates shipping instead of replacing the current quote.
Inputs: affected checkout route, sanitized 503→200→200 responses, existing test harness.
Contract: preserve items total on failure; enable retry; successful quote replaces shipping.
Reproduction: run the named regression test on the unfixed code and capture its failing assertion.
Change: repair the smallest state transition; keep pricing and API contracts unchanged.
Acceptance: fail before/pass after; request counts 1/2/3; totals 12500/13000/13000;
            failure message and retry button work; five repeated local runs pass.
Report: root cause, changed files, exact commands/results, and API assumptions still unverified.

The expected output is a regression fixture that failed for the reported reason, a small application fix, and passing local evidence. A passing mocked test cannot establish backend correctness, real payment behavior, provider availability, or production latency. Verify one sanitized response shape against the real documented API in an authorized integration environment and record its version before treating the mock as representative.

Sources

Reviewed November 5, 2026. The shipping fixture and repair brief are original examples by Ryan VerWey. Playwright documents the routing, isolation, locator, and assertion primitives used here:

Ryan VerWey

Written by

Ryan VerWey

Ryan VerWey is a full-stack developer building tools and writing practical guides for working developers.