QA and Test Automation · Lab 34 of 35
Playwright Test Agents Lab: Plan, Generate, Heal (Safely)
Set up Playwright's planner, generator and healer agents on ShopRung: a seed test, a reviewed Markdown plan, tests in the generator's format, the test MCP tools the agents call, and a review gate in CI that lets a healer fix locators but stops it from changing expectations or skipping tests.
⏱ 60 minAdvanced💸 Free8 steps
Playwright 1.63Playwright test agentsTypeScriptPython 3.12GitHub Actions
Overview video
What you will build
A Playwright project shoprung-agents-lab set up for AI test agents, with the safety net that makes them usable:
- The agents: planner, generator and healer from
npx playwright init-agents, a seed test that resets ShopRung and logs Alice in, and a reviewed plan inspecs/coupons.md. - Two tests in the generator's format (step comments, one test per file) for SAVE10 at $50.00 and FLAT5 at $15.00. One fails with ShopRung's coupon-boundary bug, as it should.
- test_tools.py: calls
test_listandtest_runon the test MCP server, as the agents do. - review_gate.py: run against real "heals": a locator fix passes; changed expected values and a
test.fixmefail the gate. Plus the GitHub Actions job.
Before you start
- The episode behind it: Playwright test agents. Useful: Self-healing and triage.
- Playwright with TypeScript, as in lab 13, and Git, as in lab 5. ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Make the project
Node.js 22 or newer and Python 3.12 or newer. Create package.json, playwright.config.ts and requirements.txt with the contents below, install, and start a Git repository: the review gate works on Git diffs. In every terminal, set the practice password as an environment variable.
mkdir -p shoprung-agents-lab && cd shoprung-agents-lab
npm install && npx playwright install chromium
python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
git init
export ALICE_PASSWORD='Alice123!'mkdir -p shoprung-agents-lab && cd shoprung-agents-lab
npm install && npx playwright install --with-deps chromium
python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
git init
export ALICE_PASSWORD='Alice123!'mkdir shoprung-agents-lab; cd shoprung-agents-lab
npm install; npx playwright install chromium
py -m venv .venv; .venv\Scripts\Activate.ps1; pip install -r requirements.txt
git init
$env:ALICE_PASSWORD="Alice123!" Initialized empty Git repository in .../shoprung-agents-lab/.git/
Create the agents
One command; then read what it made.
Run init-agents with the loop for your AI tool: claude for Claude Code, or vscode, copilot, codex, opencode. It writes three agent definitions, a seed test, a specs folder for plans and the MCP configuration that starts Playwright's test server.
Open the three files in .claude/agents/ (or your tool's folder) and read them: they are plain Markdown prompts with a tool list. In the healer, find the lines "Fixing assertions and expected values" and "do the most reasonable thing possible to pass the test". Step 6 is the answer to them.
npx playwright init-agents --loop=claude 📝 specs/README.md - directory for test plans 🌱 tests/seed.spec.ts - default environment seed file 🤖 .claude/agents/playwright-test-generator.md - agent definition 🤖 .claude/agents/playwright-test-healer.md - agent definition 🤖 .claude/agents/playwright-test-planner.md - agent definition 🔧 .mcp.json - mcp configuration ✅ Done.
A seed test for a clean start
Every agent session starts from the same state.
The planner and generator run the seed test first, then explore from where it leaves the browser. Replace the generated tests/seed.spec.ts: reset ShopRung's data, log Alice in with the password from the environment, and check the login worked. Without a reset, agents (and tests) depend on whatever the last run left behind.
import { test, expect } from '@playwright/test';
// The start state for the agents: fresh ShopRung data, Alice logged in, on the products page.
test.describe('Test group', () => {
test('seed', async ({ page, request }) => {
await request.post('/api/test/reset');
await page.goto('/#/login');
await page.getByRole('textbox', { name: 'Email' }).fill('alice@shoprung.test');
await page.getByRole('textbox', { name: 'Password' }).fill(process.env['ALICE_PASSWORD']!);
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByText('Hi, Alice Shah')).toBeVisible();
});
}); - Fresh seed data before every session.line 6
- The password stays out of the files the agents read and write.line 9
npx playwright test tests/seed.spec.ts 1 passed
A plan, reviewed by a tester
The cheapest place to catch a wrong expectation.
With an AI tool, ask the planner: "Explore the cart and coupons from the seed and save a plan for SAVE10 and FLAT5." It saves Markdown in specs/. Then review it against the requirements: an agent only knows what the screen showed, not that SAVE10 must apply at exactly $50.00 (PRICE-3) or that FLAT5 needs $20.00 (PRICE-4). Fix the boundaries and amounts in the plan before any code exists.
Without an AI tool, save this reviewed plan as specs/coupons.md. Its format is the planner's: a seed, numbered scenarios, steps and expected results.
# ShopRung coupons: test plan
Reviewed against the requirements PRICE-3 and PRICE-4 (a tester added the exact boundaries and amounts).
### 1. Coupons
**Seed:** `tests/seed.spec.ts`
#### 1.1 SAVE10 applies at exactly $50.00 (PRICE-3)
**Steps:**
1. Open the Clean Code Notebook ($12.50) and add 4 to the cart ($50.00)
2. Open the cart and apply the code SAVE10
**Expected:**
- The message "Coupon applied" appears
- Discount is -$5.00, shipping $4.99, total $49.99
#### 1.2 FLAT5 is refused at $15.00 (PRICE-4)
**Steps:**
1. Open the Green Build Mug ($15.00) and add 1 to the cart
2. Open the cart and apply the code FLAT5
**Expected:**
- The message "This coupon needs a subtotal of at least $20.00" appears
- Discount is -$0.00, total $19.99 - The generator runs this first.line 6
- Exactly at the limit: added by the reviewer from PRICE-3.line 10
- Expected values come from the requirement, not from the screen.line 15
Generated tests, one per file
Tests from the plan, then proven against a bug.
With an AI tool, ask the generator: "Generate tests for every scenario in specs/coupons.md." It performs each step in a real browser, reads the log of what worked and writes one test per file, with each plan step as a comment. Without one, create these two files, written in the generator's format from the same plan.
Run them: both pass. Then switch on ShopRung's coupon-boundary bug, where SAVE10 needs more than $50.00: the SAVE10 test fails at "Coupon applied". Leave the bug on for the next step.
// spec: specs/coupons.md
// seed: tests/seed.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Coupons', () => {
test('SAVE10 applies at exactly $50.00 (PRICE-3)', async ({ page, request }) => {
await request.post('/api/test/reset');
await page.goto('/#/login');
await page.getByRole('textbox', { name: 'Email' }).fill('alice@shoprung.test');
await page.getByRole('textbox', { name: 'Password' }).fill(process.env['ALICE_PASSWORD']!);
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByText('Hi, Alice Shah')).toBeVisible();
// 1. Open the Clean Code Notebook ($12.50) and add 4 to the cart ($50.00)
await page.goto('/#/product/1');
await page.getByRole('spinbutton', { name: 'Quantity' }).fill('4');
await page.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByRole('alert')).toHaveText('Added to cart');
// 2. Open the cart and apply the code SAVE10
await page.goto('/#/cart');
await page.getByRole('textbox', { name: 'Coupon code' }).fill('SAVE10');
await page.getByRole('button', { name: 'Apply' }).click();
await expect(page.getByRole('alert')).toHaveText('Coupon applied');
await expect(page.getByTestId('discount')).toHaveText('-$5.00');
await expect(page.getByTestId('shipping')).toHaveText('$4.99');
await expect(page.getByTestId('total')).toHaveText('$49.99');
});
}); - The generator links each test to its plan and seed.line 1
- One comment per plan step.line 15
- $50.00 - $5.00 + $4.99 shipping.line 29
// spec: specs/coupons.md
// seed: tests/seed.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Coupons', () => {
test('FLAT5 is refused at $15.00 (PRICE-4)', async ({ page, request }) => {
await request.post('/api/test/reset');
await page.goto('/#/login');
await page.getByRole('textbox', { name: 'Email' }).fill('alice@shoprung.test');
await page.getByRole('textbox', { name: 'Password' }).fill(process.env['ALICE_PASSWORD']!);
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByText('Hi, Alice Shah')).toBeVisible();
// 1. Open the Green Build Mug ($15.00) and add 1 to the cart
await page.goto('/#/product/4');
await page.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByRole('alert')).toHaveText('Added to cart');
// 2. Open the cart and apply the code FLAT5
await page.goto('/#/cart');
await page.getByRole('textbox', { name: 'Coupon code' }).fill('FLAT5');
await page.getByRole('button', { name: 'Apply' }).click();
await expect(page.getByRole('alert')).toHaveText('This coupon needs a subtotal of at least $20.00');
await expect(page.getByTestId('discount')).toHaveText('-$0.00');
await expect(page.getByTestId('total')).toHaveText('$19.99');
});
}); npx playwright test tests/coupons
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
npx playwright test tests/couponsnpx playwright test tests/coupons
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
npx playwright test tests/couponsnpx playwright test tests/coupons
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[\"coupon-boundary\"]}'
npx playwright test tests/coupons 2 passed (2.0s)
...
1) tests/coupons/save10-at-exactly-50.spec.ts:7:7 › Coupons › SAVE10 applies at exactly $50.00 (PRICE-3)
Error: expect(locator).toHaveText(expected) failed
Expected: "Coupon applied"
...
1 failed
1 passed What the healer sees
Call the agents' test tools yourself.
The healer calls the test MCP server's test_run, reads the failures and edits the tests. Create test_tools.py and call those tools directly, with the bug still on. The server offers 89 tools, about 64,600 characters of definitions; each agent file lists only the ones it uses.
Read the failure as the healer would: the alert said "This coupon needs a subtotal of at least $50.00". The test is right and ShopRung is wrong. A healer told to "do the most reasonable thing possible to pass the test" can still edit the test. Turn the bug off after this step.
"""Call the test MCP server's tools that the agents use: test_list and test_run.
python test_tools.py
"""
import asyncio
import json
import os
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
SERVER = StdioServerParameters(command="npx", args=["playwright", "run-test-mcp-server"], env=dict(os.environ))
async def main() -> None:
async with stdio_client(SERVER) as (read, write), ClientSession(read, write) as s:
await s.initialize()
tools = (await s.list_tools()).tools
size = len(json.dumps([t.model_dump(mode="json", exclude_none=True) for t in tools]))
print(f"{len(tools)} tools, {size:,} characters")
for name in ("test_list", "test_run"):
result = await s.call_tool(name, {})
print(f"== {name}")
print("\n".join(c.text for c in result.content if c.type == "text").strip()[:1500])
if __name__ == "__main__":
asyncio.run(main()) - The same server .mcp.json starts for your AI tool.line 12
- The healer's first two moves.line 21
python test_tools.py
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'python test_tools.py
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'python test_tools.py
curl.exe -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{\"enabled\":[]}' 89 tools, 64,576 characters
== test_list
Listing tests:
[id=...] coupons/flat5-refused-at-15.spec.ts:7:7 › Coupons › FLAT5 is refused at $15.00 (PRICE-4)
[id=...] coupons/save10-at-exactly-50.spec.ts:7:7 › Coupons › SAVE10 applies at exactly $50.00 (PRICE-3)
[id=...] seed.spec.ts:5:7 › Test group › seed
Total: 3 tests in 3 files
== test_run
Running 3 tests using 1 worker
✓ 1 ... FLAT5 is refused at $15.00 (PRICE-4) (546ms)
✘ 2 ... SAVE10 applies at exactly $50.00 (PRICE-3) (5.5s)
✓ 3 ... seed (380ms)
...
11 × locator resolved to <div id="toast" role="alert" class="toast err" aria-live="assertive">This coupon needs a subtotal of at least $50.00</div> A review gate for heals
Let locator fixes through; stop weakened tests.
Create review_gate.py. It reads git diff of the tests folder against a base and flags two kinds of change: removed or changed expectations (lines with expect(, toHaveText(, toBe( ...) and new weakeners: test.fixme, test.skip, .only, retries, longer timeouts and fixed sleeps. Locator changes pass. Create test_review_gate.py and run its tests, then commit everything as the reviewed baseline.
"""A review gate for healed or generated tests: fail when a change weakens what the tests check.
python review_gate.py origin/main # compare the working tree with a branch or commit
Locator changes pass. Changed or removed expectations, new skips, fixmes, .only, retries, longer timeouts and sleeps
fail the gate, so a person must review them against the requirement.
"""
import re
import subprocess
import sys
EXPECTATION = re.compile(r"\bexpect\(|\btoHaveText\(|\btoBe\(|\btoEqual\(|\btoContainText\(|\btoMatch")
WEAKENERS = {
"test.fixme": re.compile(r"\btest\.fixme\b"),
"test.skip": re.compile(r"\btest\.skip\b"),
".only": re.compile(r"\.only\("),
"retries": re.compile(r"\bretries\s*[:=]"),
"a longer timeout": re.compile(r"\btimeout\s*[:=(]"),
"a fixed sleep": re.compile(r"waitForTimeout\(|setTimeout\("),
}
def diff(base: str) -> str:
return subprocess.run(["git", "diff", "--unified=0", base, "--", "tests"], capture_output=True, text=True, check=True).stdout
def findings(patch: str) -> list[str]:
found, file = [], "?"
for line in patch.splitlines():
if line.startswith("+++ "):
file = line[6:] if line.startswith("+++ b/") else line[4:]
elif line.startswith("-") and not line.startswith("---") and EXPECTATION.search(line):
found.append(f"{file}: expectation changed or removed: {line[1:].strip()}")
elif line.startswith("+") and not line.startswith("+++"):
for name, rx in WEAKENERS.items():
if rx.search(line):
found.append(f"{file}: adds {name}: {line[1:].strip()}")
return found
def main() -> None:
base = sys.argv[1] if len(sys.argv) > 1 else "HEAD"
problems = findings(diff(base))
if not problems:
print("review gate: passed (no weakened tests)")
return
for p in problems:
print("NEEDS REVIEW", p)
print(f"review gate: {len(problems)} change(s) need a person to check them against the requirement")
sys.exit(1)
if __name__ == "__main__":
main() - A removed expectation line means what the test checks has changed.line 12
- The healer's way out when it believes the test is right: it still turns CI green.line 14
- A failing gate does not forbid the change: it requires a person.line 50
from review_gate import findings
LOCATOR_ONLY = """+++ b/tests/coupons/save10.spec.ts
- await page.getByRole('button', { name: 'Apply' }).click();
+ await page.getByRole('button', { name: /apply/i }).click();
"""
EXPECTATION = """+++ b/tests/coupons/save10.spec.ts
- await expect(page.getByTestId('discount')).toHaveText('-$5.00');
+ await expect(page.getByTestId('discount')).toHaveText('-$0.00');
"""
FIXME = """+++ b/tests/coupons/save10.spec.ts
+ test.fixme('SAVE10 applies at exactly $50.00 (PRICE-3)', async ({ page, request }) => {
"""
def test_a_locator_change_passes():
assert findings(LOCATOR_ONLY) == []
def test_a_changed_expectation_needs_review():
assert findings(EXPECTATION) == ["tests/coupons/save10.spec.ts: expectation changed or removed: await expect(page.getByTestId('discount')).toHaveText('-$5.00');"]
def test_a_fixme_needs_review():
assert findings(FIXME)[0].startswith("tests/coupons/save10.spec.ts: adds test.fixme") node_modules/
test-results/
playwright-report/
__pycache__/
.env.test pytest -q test_review_gate.py
git add -A && git commit -m "Reviewed coupon tests" ... [100%] 3 passed in 0.01s [main (root-commit) ...] Reviewed coupon tests
Three heals, through the gate
See which changes pass and which need a person.
Make three changes a healer could make, one at a time, run the gate after each, and undo with git checkout. 1. A locator change (the Apply button found by a case-insensitive name): the gate passes. 2. The "make it pass" heal: expect the refusal message, a $0.00 discount and $54.99 total. With the bug on, this healed test passes: the bug would ship. The gate flags all three expectations. 3. test.fixme: the test is skipped and CI is green; the gate flags it.
Commands for macOS and Linux (on Windows, make the same edits in your editor):
F=tests/coupons/save10-at-exactly-50.spec.ts
sed -i '' "s/name: 'Apply' }/name: \/apply\/i }/" $F; python review_gate.py HEAD; git checkout $F
sed -i '' "s/toHaveText('Coupon applied')/toHaveText('This coupon needs a subtotal of at least \$50.00')/; s/toHaveText('-\$5.00')/toHaveText('-\$0.00')/; s/toHaveText('\$49.99')/toHaveText('\$54.99')/" $F; python review_gate.py HEAD; git checkout $F
sed -i '' "s/ test('SAVE10/ test.fixme('SAVE10/" $F; python review_gate.py HEAD; git checkout $FF=tests/coupons/save10-at-exactly-50.spec.ts
sed -i "s/name: 'Apply' }/name: \/apply\/i }/" $F; python review_gate.py HEAD; git checkout $F
sed -i "s/toHaveText('Coupon applied')/toHaveText('This coupon needs a subtotal of at least \$50.00')/; s/toHaveText('-\$5.00')/toHaveText('-\$0.00')/; s/toHaveText('\$49.99')/toHaveText('\$54.99')/" $F; python review_gate.py HEAD; git checkout $F
sed -i "s/ test('SAVE10/ test.fixme('SAVE10/" $F; python review_gate.py HEAD; git checkout $F# make each edit in your editor, then:
python review_gate.py HEAD
git checkout tests/coupons/save10-at-exactly-50.spec.ts review gate: passed (no weakened tests)
NEEDS REVIEW tests/coupons/save10-at-exactly-50.spec.ts: expectation changed or removed: await expect(page.getByRole('alert')).toHaveText('Coupon applied');
NEEDS REVIEW tests/coupons/save10-at-exactly-50.spec.ts: expectation changed or removed: await expect(page.getByTestId('discount')).toHaveText('-$5.00');
NEEDS REVIEW tests/coupons/save10-at-exactly-50.spec.ts: expectation changed or removed: await expect(page.getByTestId('total')).toHaveText('$49.99');
review gate: 3 change(s) need a person to check them against the requirement
NEEDS REVIEW tests/coupons/save10-at-exactly-50.spec.ts: adds test.fixme: test.fixme('SAVE10 applies at exactly $50.00 (PRICE-3)', async ({ page, request }) => {
review gate: 1 change(s) need a person to check them against the requirement Run the gate on every pull request
Healed tests arrive as pull requests, never as direct commits.
Add the workflow. On every pull request that touches tests/, it compares the branch with its base and fails when tests were weakened, so a person must review the change against the requirement before merging. Configure your agent to open a pull request for every heal, and never to push to the main branch.
name: review-gate
on:
pull_request:
paths: ["tests/**"]
permissions:
contents: read
jobs:
gate:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Weakened tests need a human review
env:
BASE_REF: ${{ github.base_ref }}
run: python review_gate.py "origin/$BASE_REF" - The full history, so the base branch is there to compare with.line 17
- The base branch name comes through an environment variable, never pasted into the script.line 26
actionlint
git add -A && git commit -m "Review gate for healed tests" (no output from actionlint: the workflow is valid)
Check it works
npx playwright test passes on a normal ShopRung, and the SAVE10 test fails with coupon-boundary on.
python review_gate.py HEAD passes after a locator-only edit, and fails after changing an expected value or adding test.fixme.
npx playwright test
pytest -q test_review_gate.pynpx playwright test
pytest -q test_review_gate.pynpx playwright test
pytest -q test_review_gate.py 3 passed ... 3 passed in 0.01s
Troubleshooting
init-agents asks which loop, or creates files for the wrong tool.
Pass --loop= with your tool: claude, vscode, copilot, codex or opencode.
The seed fails at "Hi, Alice Shah".
ALICE_PASSWORD is not set in this terminal, or ShopRung is not running at BASE_URL.
fatal: bad revision 'HEAD' from the gate.
Commit once first (step 6); the gate compares against a commit.
The gate flags a change you meant to make.
That is its job: review the change against the requirement, and approve the pull request with the requirement id in the description.
The healer keeps editing a test that fails because of a real bug.
Stop it, file the bug, and keep the test red. A red test that matches the requirement is doing its job.
What changes in production
- Teams use the planner and generator for drafts from reviewed plans, and the healer for locator and timing fixes, always through pull requests.
- A gate like this runs in CI on test changes; changed expectations need a reviewer and a requirement id.
- Every fixme or skip has a bug ticket and an owner, and is counted so it cannot pile up silently.
- Agent definitions are versioned with the repo and edited like code, for example to forbid editing expected values.
Interview angle
“How would you use Playwright's healer agent safely?”
Only behind a review gate. Its own instructions allow fixing assertions and expected values to make a test pass. In our lab, the healed version of a SAVE10 test passed while ShopRung's coupon bug was on: the bug would have shipped. So heals come as pull requests, and a CI gate reads the diff: locator changes pass, while changed expectations, fixmes, skips, retries and sleeps fail until a person checks them against the requirement. A seed resets data, and plans are reviewed before generation.
Clean up
Practice
These run in your browser and check your answer.
Spot a weakened test
Write weakened(line) that returns True for an added diff line (starting with "+") that adds test.fixme, test.skip, .only( or waitForTimeout(, and False otherwise.
def weakened(line):
return "fixme" in line
Hint
Check line.startswith("+") first, then look for any of the four markers.
The full project
Every file from this lab, as it is after the last step.