Developer writing automated tests for AI-generated code

Playwright E2E Tests for AI-Generated UIs: Prompts and a Minimal Setup

Playwright E2E tests for AI-generated UIs catch what unit tests miss — the button AI styled beautifully but wired to the wrong handler, the form that submits twice, the modal that traps keyboard users. Vibe-coded apps change fast; without a thin E2E safety net, every prompt is a regression bet. This guide gives copy-paste prompts and a minimal Playwright setup for Next.js that a solo builder can run in CI in under ten minutes. Updated December 2026.

End-to-end test runner executing browser automation against an AI-generated web application UI
E2E tests are insurance on the paths that actually pay your bills — signup, checkout, core workflow.

Foundation: how to write tests for AI-generated code covers Vitest first — add Playwright after you have a deployed URL. Wire into GitHub Actions CI/CD so PRs cannot merge with broken critical flows.

Table of contents

  1. Why E2E for vibe-coded UIs
  2. Minimal Playwright setup
  3. Sample spec to copy
  4. Prompts for generating tests
  5. Selectors that survive AI refactors
  6. Auth and test data fixtures
  7. Running in CI against Preview
  8. Flaky test hygiene
  9. FAQ

Why E2E for vibe-coded UIs

AI excels at generating components that look correct and fail subtly:

  • Link goes to # placeholder
  • Server action succeeds but client shows error toast
  • Responsive layout hides submit button on mobile width
  • Optimistic UI never rolls back on 500

Unit tests mock the world. E2E exercises real browser, network, and hydration. You need fewer than you think — three to seven specs on critical paths beat fifty brittle snapshots.

Priority flows to cover first:

  1. Signup or login
  2. Core value action (create project, send message, run report)
  3. Checkout or upgrade if monetized
  4. Settings save

Minimal Playwright setup

In your Next.js repo root:

  1. npm init playwright@latest — choose TypeScript, tests folder e2e, add GitHub Actions workflow yes
  2. Add scripts to package.json: "test:e2e": "playwright test"
  3. Set baseURL in playwright.config.ts from process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:3000'
  4. For local: npm run build && npm run start in one terminal, npm run test:e2e in another — or use webServer block in config to auto-start dev server

Prompt: “Add Playwright to Next.js 15 repo. Config with webServer running npm run dev, baseURL localhost:3000, retries 2 on CI only, screenshot on failure, trace on first retry.”

Keep @playwright/test version pinned — AI sometimes mixes Playwright 1.x API with outdated examples.

Sample spec to copy

Minimal smoke test for marketing + auth shell — adapt selectors to your app:

// e2e/smoke.spec.ts
import { test, expect } from '@playwright/test';

test.describe('critical paths', () => {
  test('homepage loads and nav links work', async ({ page }) => {
    await page.goto('/');
    await expect(page).toHaveTitle(/Vibe|YourApp/i);
    await expect(page.getByRole('link', { name: /sign in|log in/i })).toBeVisible();
  });

  test('login page shows validation errors', async ({ page }) => {
    await page.goto('/login');
    await page.getByRole('button', { name: /sign in|log in/i }).click();
    await expect(page.getByText(/email|required/i).first()).toBeVisible();
  });

  test('authenticated dashboard', async ({ page }) => {
    // Use storageState from auth.setup.ts in real suite
    await page.goto('/dashboard');
    await expect(page.getByRole('heading', { name: /dashboard|projects/i })).toBeVisible();
  });
});

Auth setup file pattern — run once, save cookies:

// e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const authFile = 'e2e/.auth/user.json';

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel(/email/i).fill(process.env.E2E_USER_EMAIL!);
  await page.getByLabel(/password/i).fill(process.env.E2E_USER_PASSWORD!);
  await page.getByRole('button', { name: /sign in/i }).click();
  await expect(page).toHaveURL(/dashboard/);
  await page.context().storageState({ path: authFile });
});

Reference storageState: authFile in playwright.config.ts for authenticated projects. Store test user in Preview database — never production credentials in repo.

Playwright test code in editor with browser test runner showing passing end-to-end specs
Start with smoke.spec.ts — expand only when a real user path breaks without a test.

Prompts for generating tests

Use after minimal setup exists:

  • “Generate Playwright test for signup flow: fill name, email, password, submit, assert redirect to /onboarding. Use getByRole and getByLabel only.”
  • “Add test: create project from dashboard, assert project name appears in list within 5s. Use data-testid=project-row only if no accessible name.”
  • “Write Playwright test for Stripe checkout happy path using test mode card 4242 — mock webhook optional, assert success page.”
  • “Add mobile viewport test for homepage — iPhone 14 profile, assert CTA visible without horizontal scroll.”
  • “Create auth.setup.ts for magic link login using test inbox API — document env vars needed.”

Review AI-generated tests for hardcoded waits (waitForTimeout(5000)) — replace with expect(locator).toBeVisible() auto-waiting.

Selectors that survive AI refactors

Priority order (Playwright best practices):

  1. getByRole with accessible name
  2. getByLabel for form fields
  3. getByText for unique copy
  4. getByTestId for dynamic lists — add data-testid in prompt when AI omits labels
  5. CSS/XPath last resort

Prompt when UI lacks accessibility: “Add aria-label to icon-only buttons and associate labels with inputs — required for Playwright getByRole.”

Avoid selectors tied to Tailwind classes (.text-blue-500) — AI changes design tokens and tests break.

Auth and test data fixtures

E2E needs predictable data:

  • Dedicated e2e-test@yourdomain.com user in staging Supabase
  • Seed script or API route (Preview only) resetting state before suite
  • Never delete production data from tests

Multi-tenant apps: test user belongs to fixed organization_id — see multi-tenant basics for isolation tests beyond UI.

Environment variables in CI:

  • PLAYWRIGHT_BASE_URL — Vercel Preview URL
  • E2E_USER_EMAIL, E2E_USER_PASSWORD — GitHub secrets

Running in CI against Preview

GitHub Actions pattern:

  1. On pull_request, Vercel bot deploys Preview
  2. Workflow waits for deploy comment or uses deployment_status event
  3. Run npx playwright test with PLAYWRIGHT_BASE_URL set to Preview URL
  4. Upload HTML report artifact on failure

Parallel jobs: lint + unit on every push; E2E on PR to main only to save minutes. Align with existing CI/CD guide.

Rate limit Preview deploys if E2E runs every commit — balance signal vs CI cost.

Flaky test hygiene

SymptomFix
Timeout on navigationWait for networkidle sparingly; assert specific element
Element detachedRe-query after action; avoid stale locators
Race on animationDisable animations in test env CSS or wait for stable state
Date-dependent UIMock clock or freeze time in test
Parallel collisionUnique project names per test run UUID

Retries: 2 on CI only. If a test needs 3 retries to pass, fix the test or the app.

Visual regression (optional)

expect(page).toHaveScreenshot() catches AI layout drift — use sparingly on marketing hero, not every component. Store baselines in repo; update intentionally when redesign ships.

Visual tests are noisy for vibe-coded UIs that change daily — prefer behavioral assertions first.

Debugging failed runs

  • npx playwright test --ui — interactive mode locally
  • --trace on — open trace viewer for CI failures
  • Screenshot and video on failure in config
  • Reproduce with PWDEBUG=1 stepped execution

When test fails after AI refactor, paste trace + diff into Cursor — “Fix app or test: Playwright expects login redirect, got 500 on /api/auth.”

What not to E2E test

  • Every utility function — Vitest territory
  • Third-party iframe checkout internals — mock or test up to redirect
  • Email delivery content — use test API assertions
  • Pixel-perfect every breakpoint — pick one mobile + desktop

Combine layers: Zod unit tests, API integration tests, few E2E golden paths, Sentry for production unknowns.

Maintaining tests when AI changes UI

Assign one “test guardian” prompt in rules file: “When changing login or checkout UI, update e2e/*.spec.ts selectors in same PR.” CI failure is the reminder if forgotten.

Monthly: delete obsolete specs for removed features — dead tests erode trust.

Page object pattern (when specs grow)

After five specs, extract page objects:

// e2e/pages/login.page.ts
import { Page, expect } from '@playwright/test';

export class LoginPage {
  constructor(private page: Page) {}

  async goto() {
    await this.page.goto('/login');
  }

  async login(email: string, password: string) {
    await this.page.getByLabel(/email/i).fill(email);
    await this.page.getByLabel(/password/i).fill(password);
    await this.page.getByRole('button', { name: /sign in/i }).click();
    await expect(this.page).toHaveURL(/dashboard/);
  }
}

Specs call new LoginPage(page).login(...) — selector changes happen in one file. Prompt: “Refactor e2e login tests to use LoginPage class in e2e/pages/.”

Mobile and responsive E2E

AI UIs break on mobile constantly. Add project in playwright.config:

  • { name: 'mobile', use: { ...devices['iPhone 14'] } }
  • Run critical path on mobile project in CI — doubles time, catches real bugs
  • Test sticky nav, bottom sheets, and keyboard covering inputs

Playwright E2E tests for AI-generated UIs should include at least one mobile viewport on signup or checkout — where revenue and account creation happen on phones.

Security testing with Playwright

Light security checks without dedicated pentest:

  • Logged-out user cannot access /dashboard — expect redirect
  • User A cannot open User B resource URL — expect 404 or 403
  • CSRF-sensitive forms include tokens if your stack uses them

Pair with security checklist — E2E proves UI gates; RLS proves data layer.

Local developer workflow

Daily loop for vibe coders:

  1. Implement feature in Cursor
  2. Run npx playwright test e2e/smoke.spec.ts before push
  3. Push PR — CI runs full suite against Preview
  4. Merge when green

Install Playwright VS Code extension for record-and-playback to bootstrap selectors — then refactor to getByRole before committing. Recorded CSS selectors rot fast on AI redesigns.

Meta-prompt for test generation

When UI stabilizes, one-shot prompt for coverage:

“Read app/dashboard/page.tsx and app/api/projects/route.ts. Generate Playwright tests covering: list projects empty state, create project happy path, validation error on empty title. Use e2e/pages pattern. No waitForTimeout.”

Review generated tests like production code — AI tests click wrong buttons confidently.

Reporting and artifacts

On CI failure, upload:

  • playwright-report/ HTML report as artifact
  • Trace zip for failed tests
  • Screenshot on failure (config default)

Share report link in PR comment bot — reviewers reproduce visually without running locally. Playwright E2E tests for AI-generated UIs only pay off when failures are visible to future you, not buried in CI log scrollback.

Troubleshooting common setup failures

ProblemCauseFix
baseURL connection refusedwebServer not startedCheck playwright.config webServer command and port
Auth test flakySession expired mid-suiteRefresh storageState in setup; shorter suite parallelization
Preview URL 401Vercel deployment protectionBypass header secret in CI env
Test passes local, fails CITimezone or locale differenceSet TZ=UTC in CI; avoid locale-specific assertions
Browser not installedMissing playwright install in CIAdd npx playwright install –with-deps step

Most Playwright setup pain for vibe coders is environment wiring, not test syntax. Fix config once; prompts 953 generate specs for years.

FAQ

Playwright vs Cypress for Next.js?

Playwright has stronger multi-tab, auto-wait, and official parallel CI story in 2026. Cypress still fine if team already invested.

How many E2E tests?

Start with 3–7. Add one when you fix a production bug that unit tests missed.

Run against localhost or Preview?

Both — dev for speed, Preview for env parity before merge.

Do I need Docker?

No for most Vercel-hosted apps. GitHub Actions ubuntu-latest runs Playwright browsers via install-deps.

How do E2E tests interact with auth providers?

Password test user simplest; magic link via Mailosaur or provider test inbox API.

Can Playwright test API routes only?

Use request fixture for API — but that is integration test. Browser E2E is for UI integration.

How long should E2E suite run in CI?

Target under five minutes for smoke suite. Split slow checkout tests to nightly job if needed.

Should I mock Stripe in E2E?

Use Stripe test mode and test card — real redirect flow up to success page. Mock webhooks in separate integration tests.

Soft CTA: Copy the smoke spec above into e2e/smoke.spec.ts, fix three selectors, run npx playwright test --ui once. Green-light login and one core action before your next big AI UI prompt — future refactors will thank you.

Leave a Reply

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