app-exploration
Automatically map web application routes, forms, and interactions via static code analysis and Playwright browser exploration to generate a prioritized JSON inventory of e2e test scenarios.
- License 许可
- MPL-2.0
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- updated
- 1781827200000
- description
- Automatically map web application routes, forms, and interactions via static code analysis and Playwright browser exploration to generate a prioritized JSON inventory of e2e test scenarios.
- when_to_use
- Use when starting Playwright test creation for a web application from scratch, auditing coverage gaps, onboarding to an unfamiliar codebase, or after significant refactors.
03 SKILL.md 正文
App Exploration for Playwright Test Generation
When to use this skill
Use this skill when:
- Starting Playwright test creation for a web application from scratch with no existing e2e suite
- Auditing an existing test suite to identify coverage gaps against actual app routes and interactions
- Onboarding to an unfamiliar codebase and needing a complete map of testable surfaces before writing tests
- After a significant refactor or feature addition that may have invalidated existing test coverage
Do NOT use this skill if:
- You already have a complete test-scenarios.json from a prior run and the app has not changed
- The task is to write tests for a single specific component or interaction already identified
Prerequisites
Verify all of the following before proceeding:
- Playwright installed —
npx playwright --versionmust succeed. If missing, runnpm install -D @playwright/test. - Chromium binary — Run
npx playwright install chromiumif the binary is absent. - App running or startable — Either the app is already running at a known base URL, or a start command exists (
npm run dev,npm start,pnpm dev, etc.). Identify the base URL (default:http://localhost:3000orhttp://localhost:5173for Vite projects). - Read access to source — The agent must be able to read router config files, component files, and API client files in the project.
- Write access to output path — Confirm the output directory exists or can be created before Step 4.
Step 1: Static Code Analysis
Goal: build a complete list of routes and their associated data, forms, and API calls without launching a browser.
1a. Detect the frontend framework and locate the router config
Check for the following files in order. Use the first match.
| Framework | Indicator file(s) | Route source |
|---|---|---|
| Next.js App Router | app/ directory with page.tsx or page.jsx files |
Walk app/**/page.tsx — each page.tsx path segment is a route |
| Next.js Pages Router | pages/ directory |
Walk pages/**/*.tsx — filename maps to route, [param] = dynamic segment |
| React Router v6+ | src/routes.tsx, src/router.tsx, or createBrowserRouter call |
Read the routes config; extract path: values |
| SvelteKit | src/routes/ directory with +page.svelte files |
Walk src/routes/**/+page.svelte — directory path = route |
| Vue Router | src/router/index.ts or src/router.ts |
Read routes array; extract path: values |
| Remix | app/routes/ directory |
Walk app/routes/*.tsx — filename encodes route (. = /, _ = layout) |
Read the router config file (or walk the directory) and produce a flat list:
[
{ "route": "/", "label": "Home" },
{ "route": "/login", "label": "Login" },
{ "route": "/dashboard", "label": "Dashboard" },
{ "route": "/users/:id", "label": "User Detail" },
...
]
For dynamic segments (:id, [id], $id), record the pattern and note that a real ID must be substituted during browser exploration.
1b. Read component files for each route
For each route, locate the corresponding component or page file. Read it and extract:
- Form fields:
<input>,<select>,<textarea>,<Form>,react-hook-formregister()calls,zodschema field names - Data displays: table components, list renders, charts, cards — note what data entity they display
- Auth guards:
useAuth,ProtectedRoute,redirect('/login'),getServerSession, middleware imports - Navigation links:
<Link to=...>,<a href=...>,router.push(...)— these reveal routes you may have missed - Key user actions: button labels, submit handler names, mutation calls
Record per-route notes:
route: /login
forms: [{ "fields": ["email", "password"], "submitLabel": "Sign in", "validation": "zod" }]
auth_guard: false
navigation_links: ["/register", "/forgot-password"]
data_displays: []
api_calls: ["POST /api/auth/login"]
1c. Read API client and service files
Locate API client files: src/lib/api.ts, src/services/, src/api/, src/hooks/use*.ts with fetch/axios calls. For each, extract:
- HTTP method and endpoint path
- Which route component imports this function
- Whether the call requires auth headers (look for
Authorization,Bearer, cookie checks)
This creates a map of route → API dependencies used later to seed test fixture needs.
Step 2: Framework Detection
Goal: determine where tests live and avoid overwriting existing config.
2a. Detect existing test framework
Check in order:
playwright.config.tsorplaywright.config.js— Playwright is already configured; read it (see 2b).vitest.config.tswith@playwright/experimental-ct-*— component testing; separate from e2e.jest.config.*— Jest is present; Playwright will coexist, but confirm no namespace collision.- No config found — fresh setup; proceed to create
playwright.config.tsonly if explicitly instructed.
2b. Read existing playwright.config.ts if present
Extract:
testDir— where spec files go (e.g.,e2e/,tests/,__tests__/)baseURL— the app's base URL for testsprojects— which browsers are configuredwebServercommand — how the app is started for tests
If baseURL is set, use it. Otherwise default to http://localhost:3000.
2c. Determine output directory for test files
Use this priority:
testDirfromplaywright.config.tse2e/if the directory existstests/if the directory exists__tests__/if the directory exists- Create
e2e/at project root
Record the resolved test directory. All generated files go here.
Step 3: Playwright Browser Exploration
Goal: live-validate the static analysis, discover dynamic routes, and capture interactive element inventories.
3a. Script setup
Write a temporary exploration script at e2e/_explore.ts (or .js). The script is deleted after the inventory is complete. Template:
import { chromium, Page } from '@playwright/test';
import * as fs from 'fs';
const BASE_URL = process.env.BASE_URL ?? 'http://localhost:3000';
const OUTPUT_PATH = process.env.OUTPUT_PATH ?? 'e2e/test-scenarios.json';
async function explorePage(page: Page, route: string) {
const url = `${BASE_URL}${route}`;
await page.goto(url, { waitUntil: 'networkidle' });
await page.screenshot({ path: `e2e/_screenshots${route.replace(/\//g, '_') || '_home'}.png` });
const interactiveElements = await page.$$eval(
'[role="button"], button, a[href], input, select, textarea, [role="link"], [role="menuitem"]',
els => els.map(el => ({
tag: el.tagName.toLowerCase(),
type: (el as HTMLInputElement).type ?? null,
name: (el as HTMLInputElement).name ?? null,
id: el.id ?? null,
text: el.textContent?.trim().slice(0, 80) ?? null,
href: (el as HTMLAnchorElement).href ?? null,
role: el.getAttribute('role') ?? null,
ariaLabel: el.getAttribute('aria-label') ?? null,
placeholder: (el as HTMLInputElement).placeholder ?? null,
required: (el as HTMLInputElement).required ?? false,
}))
);
const forms = await page.$$eval('form', forms => forms.map(form => ({
id: form.id ?? null,
action: form.action ?? null,
method: form.method ?? 'get',
fields: Array.from(form.querySelectorAll('input, select, textarea')).map(f => ({
tag: f.tagName.toLowerCase(),
name: (f as HTMLInputElement).name,
type: (f as HTMLInputElement).type ?? null,
required: (f as HTMLInputElement).required,
placeholder: (f as HTMLInputElement).placeholder ?? null,
})),
})));
const pageTitle = await page.title();
const h1 = await page.$eval('h1', el => el.textContent?.trim()).catch(() => null);
return { route, url, pageTitle, h1, interactiveElements, forms };
}
3b. Navigate each route
For each route collected in Step 1a:
- Substitute real IDs for dynamic segments. Use IDs discovered from the app's seed data, fixtures, or visible list pages. If no real ID is available, use
1as a placeholder and mark the scenarioneeds_fixture: true. - Call
explorePage(page, route). - If the page redirects to
/loginor another route, recordauth_required: truefor that route. - After loading, check
page.url()against the requested URL. A mismatch indicates a redirect.
3c. Discover nested and dynamic routes
After exploring the static route list:
- On each explored page, collect all
<a href>values frominteractiveElementsthat start with/and are not already in the route list. - Add newly discovered routes to the exploration queue (depth-limited to 2 levels beyond the static list to avoid crawling infinitely).
- For modal and drawer triggers: identify buttons whose click reveals a dialog. Use
page.click(selector)then check for[role="dialog"],[role="alertdialog"], or.modalbecoming visible. Record modal contents with the same element extraction.
3d. Trigger error and empty states
For each form found:
- Submit with all fields empty. Record validation messages via
page.$$eval('[role="alert"], .error, [aria-live]', ...). - These become "validation" test scenarios.
For list/table pages:
- Record whether an empty state element exists (
[data-testid*="empty"],.empty-state, text matching "No results" or "Nothing here").
Step 4: Generate Scenario Inventory
Goal: combine static analysis and live exploration into a structured JSON file.
Scenario object schema
Each scenario in the output array has this shape:
{
"id": "login-happy-path",
"title": "User can log in with valid credentials",
"route": "/login",
"priority": 1,
"category": "auth",
"type": "happy-path",
"preconditions": ["user account exists in DB"],
"steps": [
"Navigate to /login",
"Fill email field with valid user email",
"Fill password field with valid password",
"Click 'Sign in' button",
"Assert redirect to /dashboard",
"Assert user name visible in header"
],
"assertions": [
{ "type": "url", "expected": "/dashboard" },
{ "type": "visible", "selector": "[data-testid='user-menu']" }
],
"api_calls": ["POST /api/auth/login"],
"fixtures_required": ["user:standard"],
"needs_fixture": false,
"auth_required": false,
"screenshot_path": "e2e/_screenshots_login.png",
"source": "static+browser"
}
Field definitions:
id— kebab-case unique identifier; no spacespriority— integer 1 (highest) to 5 (lowest)category— one of:auth,crud,navigation,validation,error,accessibility,performancetype— one of:happy-path,sad-path,edge-case,smokeneeds_fixture— true if a real DB record ID is required but not confirmedsource—static(from code only),browser(from live exploration only),static+browser(both)
Generating scenario objects
For each route and interaction discovered:
- Create one
happy-pathscenario for the primary success flow. - Create one
sad-pathscenario per form for the primary validation failure (empty submit or invalid input). - Create one
authscenario ifauth_required: truewas detected — testing that unauthenticated access redirects correctly. - Create navigation scenarios for any links that traverse major sections.
Step 5: Prioritize and Output
Sorting rules
Sort the final scenarios array by priority ascending, then by category using this order:
auth— login, logout, session expiry, protected route guardscrud— create, read, update, delete for primary data entitiesnavigation— routing, breadcrumbs, back/forward behaviorvalidation— form field validation, error messageserror— 404 pages, API error states, network failure handlingaccessibility— keyboard nav, ARIA roles, focus managementperformance— load time, lazy loading, pagination
Within each category, happy-path before sad-path before edge-case.
Output file format
Write the final inventory to the path determined in Step 2c (e.g., e2e/test-scenarios.json).
The output must be a valid JSON array:
[
{ "id": "login-happy-path", ... },
{ "id": "register-sad-path", ... },
...
]
Post-processing cleanup
After generating the inventory:
- Delete
e2e/_explore.ts(or.js). - Remove temporary screenshot files from
e2e/_screenshots/unless explicitly requested to keep them. - Log completion status and path to the generated scenarios file.
Output Example
A successful run produces e2e/test-scenarios.json:
[
{
"id": "login-happy-path",
"title": "User can log in with valid credentials",
"route": "/login",
"priority": 1,
"category": "auth",
"type": "happy-path",
"preconditions": ["user account exists in DB"],
"steps": [
"Navigate to /login",
"Fill email field with valid user email",
"Fill password field with valid password",
"Click 'Sign in' button",
"Assert redirect to /dashboard",
"Assert user name visible in header"
],
"assertions": [
{ "type": "url", "expected": "/dashboard" },
{ "type": "visible", "selector": "[data-testid='user-menu']" }
],
"api_calls": ["POST /api/auth/login"],
"fixtures_required": ["user:standard"],
"needs_fixture": false,
"auth_required": false,
"screenshot_path": "e2e/_screenshots_login.png",
"source": "static+browser"
}
]
This file serves as the blueprint for the subsequent test generation skill to write actual .spec.ts files.
04 同仓库更多 Skills
tax-filing-checklist
Walk through the steps and documents needed to file an individual federal income tax return
patient-vitals-charting
Record patient vital signs consistently and flag values outside the normal reference range
pasta-from-scratch
Make fresh egg pasta dough from scratch, roll it, and cut it into shapes
knife-sharpening
Sharpen and hone kitchen knives to keep an edge safe and effective
first-aid-response
Respond to a first aid emergency using a scene-safety-first, ABC-based (airway, breathing, circulation) approach
contract-review-basics
Review a contract draft for missing terms, ambiguous language, and risky clauses before signing