My phone went off at 3:14 AM on a Wednesday in October.
PagerDuty was yelling about billing-service v2.18.4 throwing HTTP 422 errors on /api/v2/subscriptions/upgrade. When I stumbled to my desk and opened Datadog, 114 enterprise customers had already failed to add seats to their workspaces. Support had 29 tickets sitting in Zendesk.
The weird part? Every single check on the release PR had passed. All 412 Playwright specs were green. Not a single flake, not a single retry.
I pulled up the exact test that was supposed to guard that flow: tests/e2e/billing/seat-upgrade.spec.ts. A junior engineer had generated it with an AI coding assistant four months earlier during our big "80% E2E coverage by Q3" push, and three of us—myself included—had rubber-stamped the PR because the diff looked clean and the CI badge was green.
Here is what that test actually did when the upgrade button broke: it clicked "Add 5 Seats", caught a timeout waiting for the Stripe confirmation modal because .catch(() => false) was wrapped around the assertion, and exited with code 0.
It passed. Every single time. Even when the feature was completely dead.
How We Ended Up With 412 Tests Nobody Read
Back in May, our VP of Engineering wanted faster release cycles without hiring two more QA engineers. At the time, our small platform team (four full-stack devs, one DevOps engineer, and me as Lead SDET) maintained 48 hand-written Playwright specs on GitHub Actions. They took about 4 minutes to run and caught real regressions.
Then someone demoed generating Playwright specs straight from Jira tickets and DOM snapshots. Within 18 days, our suite ballooned from 48 tests to 412. Management loved the coverage chart. Slack had celebratory emojis every time a PR added 30 new .spec.ts files.
Nobody noticed the slow rot until August.
By September, our GitHub Actions bill for ubuntu-latest 8-core runners had climbed from $890/month to $4,180/month. A single PR took 19 minutes and 42 seconds to clear E2E, even sharded across 12 parallel workers. Developers started hitting "Re-run failed jobs" without reading the trace viewer, because 30 to 40 tests flaked on any given afternoon.
And yet, bugs kept leaking into production. The October billing incident was just the one loud enough to wake me up at 3 AM.
So I blocked off two days, pulled every single .spec.ts file into a spreadsheet, and audited all 412 tests by hand. (Glamorous work.) By Friday evening, I opened a PR that deleted 382 of them.
The Five Ways AI-Generated Playwright Tests Lied to Us
Almost every bad test fell into one of five patterns. Not because the AI was "dumb"—it wrote syntactically valid TypeScript that looked great in a 400-line GitHub diff—but because LLMs optimize for passing the run rather than proving the system works.
1. Assertions That Could Never Fail
This was the culprit behind the 3 AM billing outage, and I found variations of it in 94 different files.
When an AI assistant runs a generated test locally and hits an async race condition, its default instinct is to make the error go away. Sometimes that means adding a try/catch. Sometimes it means asserting on something that is always on the page anyway.
Here is an almost verbatim version of what was sitting in seat-upgrade.spec.ts:
// What got merged in June (passed even when POST /upgrade returned 422) test('user can upgrade workspace seats', async ({ page }) => { await page.goto('/settings/billing'); await page.getByRole('button', { name: 'Manage Seats' }).click(); await page.getByLabel('Additional seats').fill('5'); await page.getByRole('button', { name: 'Confirm Upgrade' }).click(); // AI added this fallback after the modal flaked once during generation const modalVisible = await page .locator('[data-testid="upgrade-success-modal"]') .isVisible() .catch(() => false); if (modalVisible) { await expect(page.getByText('Seats updated')).toBeVisible(); } // Fallback assertion that ALWAYS passes because the navbar is still there await expect(page.getByRole('heading', { name: 'Billing' })).toBeVisible(); }); Look at that if (modalVisible) block. If the modal appears, it checks the text. If the backend throws a 422 and the modal never renders, it silently skips the check and asserts that the word "Billing" is still on the page.
I missed it in code review because I skimmed the bottom expect(...) and saw a getByRole locator. My fault, honestly. When a PR has 14 new test files in it, your brain goes on autopilot around file number four.
2. waitForTimeout Disguised as Stability
I counted 217 calls to page.waitForTimeout() across the 412 specs.
Most of them were between 1500 and 5000 milliseconds. Why? Because when you ask an AI to fix a flaky click on a React drawer animation or a debounced search input, await page.waitForTimeout(3000) is the fastest way to make the local test turn green.
Multiply 217 arbitrary sleeps by 3 seconds average, add CI retries, and you get ~11 minutes of pure dead air per pipeline run. We were literally paying AWS/GitHub compute rates to watch Node.js setTimeout count to three.
3. Brittle CSS Chains That Broke on Every Tailwind Refactor
For components that lacked data-testid attributes, the generated tests fell back to DOM archaeology:
await page.locator('div.flex.flex-col.gap-4 > div:nth-child(3) > button.bg-indigo-600').click(); Whenever a frontend dev changed gap-4 to gap-6 or wrapped a card in a new container, 18 tests exploded. Nobody wanted to debug why div:nth-child(3) stopped matching, so engineers either asked the AI to regenerate the whole file (adding more .catch(() => false) bands-aids) or disabled the spec with test.skip().
At the peak in September, we had 47 skipped tests that nobody owned.
4. Testing Mocked Fantasy Land
About 60 of the specs tested complex multi-step forms by intercepting every backend call with page.route() and returning hardcoded JSON fixtures that the AI invented on the spot.
Those fixtures did not match our Go backend's actual response shape. One test mocked /api/v2/invoices with total_cents: 4900, while production returned amount_due: "49.00" as a formatted string. The test was 100% green and 100% fiction. (If you want the full horror story on why over-mocking breaks production, this breakdown—well, we learned that lesson separately the hard way too.)
5. Duplicate Flows With Different Names
Because different developers prompted AI assistants for different Jira tickets over four months, we ended up with 11 separate tests that all logged in, navigated to /projects, created a project, and checked that the project name appeared in the sidebar.
Eleven. Running on every single commit.
What We Kept vs. What We Burned
Out of 412 specs, 30 survived the purge. Twenty-two of those were from our original 48 pre-AI suite, and eight were AI-drafted tests that a human had heavily rewritten around real API responses.
Here is the exact before-and-after from the seat-upgrade.spec.ts rewrite we shipped on that Thursday afternoon:
// Rewritten: verifies the actual HTTP contract, UI state, and reload persistence test('user can upgrade workspace seats and persist new limit', async ({ page }) => { await page.goto('/settings/billing'); await page.getByRole('button', { name: 'Manage Seats' }).click(); await page.getByLabel('Additional seats').fill('5'); const [upgradeRes] = await Promise.all([ page.waitForResponse( (res) => res.url().includes('/api/v2/subscriptions/upgrade') && res.request().method() === 'POST' ), page.getByRole('button', { name: 'Confirm Upgrade' }).click(), ]); expect(upgradeRes.status()).toBe(200); const body = await upgradeRes.json(); expect(body.new_seat_limit).toBeGreaterThanOrEqual(5); await expect(page.getByTestId('upgrade-success-modal')).toBeVisible(); // Reload to prove the database actually committed, not just React state await page.reload(); await expect(page.getByTestId('current-seat-count')).toContainText( String(body.new_seat_limit) ); }); Notice three things here:
- No
try/catch, noif (visible)branch. If the modal does not show up, the test dies. Promise.allpairs the click withpage.waitForResponseso a 422 fails immediately with the status code instead of timing out 30 seconds later on a missing DOM node.page.reload()proves the change hit Postgres and survived a fresh render.
The 90-Line AST Guard That Replaced Human Willpower
Deleting 382 tests felt great for about 48 hours. Then I realized something obvious: without an automated gate, someone on the team would paste another AI-generated test into a PR by next Tuesday, and we would be right back where we started.
Code review does not scale against 500-line test diffs. Humans get tired at 5 PM on a Friday and hit "Approve."
So instead of writing a Confluence doc nobody would read, I spent a Saturday morning writing a standalone TypeScript AST checker using the typescript compiler API (which was already in node_modules). It runs in CI in 14 seconds and fails the build before GitHub Actions even boots a Playwright browser.
Here is the exact script we dropped into scripts/audit-playwright-tests.ts:
import fs from 'node:fs'; import path from 'node:path'; import ts from 'typescript'; interface Violation { file: string; line: number; rule: string; } const TEST_DIR = path.resolve('tests/e2e'); const BANNED_METHODS = new Set(['waitForTimeout']); function collectSpecFiles(dir: string): string[] { const entries = fs.readdirSync(dir, { withFileTypes: true }); return entries.flatMap((entry) => { const fullPath = path.join(dir, entry.name); if (entry.isDirectory()) return collectSpecFiles(fullPath); return entry.name.endsWith('.spec.ts') ? [fullPath] : []; }); } function auditFile(filePath: string): Violation[] { const sourceText = fs.readFileSync(filePath, 'utf8'); const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true); const violations: Violation[] = []; let expectCount = 0; const lineOf = (node: ts.Node) => sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1; function visit(node: ts.Node) { // Rule 1: Ban page.waitForTimeout() if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { const propName = node.expression.name.text; if (BANNED_METHODS.has(propName)) { violations.push({ file: filePath, line: lineOf(node), rule: `Banned call "${propName}". Wait on a network response or locator state instead.`, }); } // Rule 2: Ban .catch(() => false) / .catch(() => null) swallowing checks if (propName === 'catch' && node.arguments.length === 1) { const argText = node.arguments[0].getText(sourceFile); if (/=>\s*(false|null|undefined|\{\s*\})/.test(argText)) { violations.push({ file: filePath, line: lineOf(node), rule: 'Silent .catch() fallback detected. Let assertions fail loudly.', }); } } } // Rule 3: Ban conditional expect() inside if-blocks if (ts.isIfStatement(node) && node.getText(sourceFile).includes('expect(')) { violations.push({ file: filePath, line: lineOf(node), rule: 'Conditional expect() inside if-statement. Tests must be deterministic.', }); } // Rule 4: Flag brittle nth-child CSS selectors if (ts.isStringLiteral(node) && /:nth-child\(|>.*>.*>/.test(node.text)) { violations.push({ file: filePath, line: lineOf(node), rule: 'Brittle CSS chain / nth-child selector. Use getByRole, getByLabel, or data-testid.', }); } if (ts.isCallExpression(node) && node.expression.getText(sourceFile) === 'expect') { expectCount++; } ts.forEachChild(node, visit); } visit(sourceFile); if (expectCount === 0) { violations.push({ file: filePath, line: 1, rule: 'Zero expect() calls found in spec file.', }); } return violations; } const files = collectSpecFiles(TEST_DIR); const allViolations = files.flatMap(auditFile); if (allViolations.length > 0) { for (const v of allViolations) { console.error(`${path.relative(process.cwd(), v.file)}:${v.line} — ${v.rule}`); } process.exit(1); } console.log(`Playwright AST audit passed across ${files.length} spec files.`); And here is the GitHub Actions job that runs it as a hard prerequisite before e2e-shards is allowed to start:
jobs: playwright-lint: runs-on: ubuntu-latest timeout-minutes: 3 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci --ignore-scripts - run: npx tsx scripts/audit-playwright-tests.ts e2e-tests: needs: playwright-lint runs-on: ubuntu-latest strategy: matrix: shard: [1/4, 2/4, 3/4, 4/4] steps: - uses: actions/checkout@v4 - run: npx playwright test --shard=${{ matrix.shard }} The first week we turned this on, it blocked three PRs from merging—two of them mine, honestly, where I had left a quick waitForTimeout in while debugging locally and forgot to clean it up.
What Changed After the Purge
By November, our numbers looked completely different:
- Spec count: 412 down to 34 (we added 4 real contract-backed tests back for critical billing and auth paths).
- CI runtime: 19m 42s down to 4m 18s.
- Monthly runner spend: $4,180 down to $890.
- Flake rate: ~8.5% per run down to 0.4% (mostly transient staging DNS hiccups).
- Escaped billing/checkout bugs over the next 90 days: Zero.
Did we ban AI coding tools for writing tests? No. I still use them to scaffold Playwright page objects or generate boring TypeScript types from an OpenAPI schema.
But we stopped letting AI decide what to assert, and we stopped treating test file count as a proxy for safety. A test suite with 34 honest assertions you actually trust beats 412 green lies every day of the week—especially at 3:14 AM.
