Playwright API Corner Case Test Generator
Generate comprehensive API corner case tests using Playwright's APIRequestContext. Systematically discover endpoints, then produce tests from a structured corner case catalog.
Usage: /playwright-api <test-file-path or description>
The argument is either:
- A path to an existing Playwright E2E test — the skill reads it, runs it to capture network traffic, analyzes which APIs it exercises, and generates corner case tests for those endpoints.
- A free-form description of the API endpoints to test (e.g.,
Corner cases for the booking CRUD API, Test edge cases on POST /api/users).
Hard Rules
- Every invocation MUST end by asking the user whether to run the tests. No exceptions.
- Never hardcode base URLs in tests or API helpers.
- Always check existing API tests and helpers before creating new ones.
- Never mock API responses — tests hit real endpoints.
- Always present the discovered API map for user confirmation before generating corner cases.
- Always present the corner case list for user selection before generating test code.
- Never guess at API schemas — discover from code, specs, traces, or ask the user.
Workflow
Phase 0: Project Discovery
Automatically scan the project before any user interaction.
- Parse
$ARGUMENTS to determine input type:
- If the argument is a file path that exists on disk and ends in
.spec.ts or .test.ts → test file mode (Branch A).
- Otherwise → description mode (Branch B).
- Search for Playwright configuration:
- Look for
playwright.config.ts, playwright.config.js
- Check
package.json for @playwright/test dependency
- If Playwright is not installed, inform the user and stop:
"This project does not have Playwright configured. Run npm init playwright@latest to set it up, then re-invoke this skill."
- Read the Playwright config and extract:
baseURL configuration
- Test directory location (
testDir)
globalSetup / storageState (for auth pattern detection)
- Custom fixtures
- Scan for existing API tests and helpers:
- Glob:
**/*.api.spec.ts, **/*.api.test.ts
- Glob:
**/api-helpers/**, **/helpers/*.api.ts
- Record: file path, describe block names, test names, helper class names
- Scan for API route definitions in source code:
- Glob:
**/routes/**, **/controllers/**, **/*.controller.ts, **/*.routes.ts
- Look for Express routers, NestJS controllers, FastAPI routes, or similar
- Scan for API specifications:
- Glob:
**/openapi.*, **/swagger.*, **/*.openapi.yaml, **/*.openapi.json
- Scan for DTOs and type definitions:
- Glob:
**/dto/**, **/schemas/**, **/models/**, **/types/**
- Detect auth pattern: check for
storageState in config, globalSetup files, extraHTTPHeaders, Bearer token patterns in existing tests.
Phase 1: Input Analysis
Branch A — Test file
- Read the E2E test file.
- Read all imported Page Object Models, helpers, and fixtures.
- Summarize what user flow the E2E test exercises.
- Extract API-related patterns from the code:
waitForResponse / waitForRequest calls → endpoint URLs and methods
page.route() / page.on('request') → intercepted endpoints
- URL string literals matching API patterns (
/api/, /v1/, etc.)
fetch() calls in evaluated scripts
- Present the initial summary:
"This E2E test exercises the booking creation flow. I found these API calls in the code: POST /api/bookings, GET /api/bookings/{id}. I'll run the test next to discover any additional endpoints."
Branch B — Description
- Analyze the description together with project context from Phase 0.
- Ask the user 3-5 focused questions, selected based on what is unclear:
- Which specific API endpoints are involved? (list any you know)
- What HTTP methods and resource types? (REST CRUD, RPC, GraphQL?)
- What authentication is required?
- Are there request/response schemas, DTOs, or type definitions available?
- What does "success" look like for the happy path?
- Wait for answers before proceeding.
Phase 2: API Discovery
Both branches: ask about API specifications first.
"Do you have an API specification (OpenAPI/Swagger, Postman collection, or similar) for these endpoints? If so, where is it?"
If the user provides a spec, read and parse it to extract:
- Endpoints (method + path)
- Request schemas (required/optional fields, types, constraints like maxLength, enum, pattern)
- Response schemas per status code
- Authentication requirements
This spec becomes the primary source of truth for corner case generation — it reveals constraints that code analysis alone may miss.
Branch A — Test file (trace-based discovery)
- Run the E2E test with trace capture:
npx playwright test <file> --trace on --reporter=list
- If the test passes: parse the trace to extract all HTTP requests:
- HTTP method and URL path
- Request headers and body shape
- Response status code and body shape
- Build the API endpoint map
- If the test fails or cannot run: inform the user and fall back to the code-only analysis from Phase 1.
- Merge code-analysis endpoints with trace-discovered endpoints.
- Cross-reference with the API spec (if provided) to fill in schema details, constraints, and additional endpoints not exercised by the E2E test.
Branch B — Description (code-based discovery)
- Search source code for route definitions matching the described endpoints.
- Read DTOs/interfaces for request/response shapes.
- Cross-reference with the API spec (if provided) for complete schema details.
Both branches converge
Present the API Endpoint Map to the user:
## Discovered API Endpoints
| # | Method | Path | Request Body | Success Status | Key Constraints |
|---|--------|-------------------|----------------------|----------------|-----------------------|
| 1 | POST | /api/bookings | { name*, date* } | 201 | name: maxLen 100 |
| 2 | GET | /api/bookings/:id | — | 200 | id: positive integer |
| 3 | GET | /api/bookings | — | 200 | paginated, filterable |
* = required field
Auth: Bearer token via storageState
Base URL: from playwright.config.ts
Is this complete? Any endpoints to add or remove?
Wait for user confirmation before proceeding.
Phase 3: Corner Case Analysis
- Load references/corner-case-catalog.md.
- For each confirmed endpoint, walk through every category in the catalog:
- Check the Applies to tag — skip categories that don't match.
- Generate concrete test case ideas using the endpoint's actual fields and types.
- If an API spec was provided, use its constraints to generate more targeted corner cases:
- Field has
maxLength: 100 → test lengths 100 (valid), 101 (invalid), and 0 (empty).
- Field is an enum → test a value not in the enum.
- Field has a regex pattern → test a string that violates the pattern.
- Field has min/max range → test at boundaries and beyond.
- Present the full list grouped by endpoint with category tags:
## Corner Cases for POST /api/bookings
### Validation — Required Fields
1. Empty request body → expect 400
2. Missing "name" → expect 400
3. Missing "date" → expect 400
4. Null for "name" → expect 400
### Validation — Boundary Values
5. Name at max length (100 chars) → expect 201
6. Name exceeding max length (101 chars) → expect 400
7. Empty string for "name" → expect 400
### Auth Edge Cases
8. No auth token → expect 401
9. Expired token → expect 401
...
## Corner Cases for GET /api/bookings/:id
### Resource Not Found
10. Non-existent ID → expect 404
11. Non-numeric ID → expect 400
...
Select which corner cases to implement (e.g., "all", "1-9", "skip auth cases"):
Wait for user selection.
Phase 4: Similarity Search
Avoid duplicating existing tests. Find reusable code.
- Search existing API test files for overlapping endpoint coverage:
- URL/route overlap with discovered endpoints
- Keyword matching against
test.describe and test() names
- Search existing API helpers for reusable client classes.
- If overlap is found, present it:
Found existing API tests that may overlap:
1. tests/api/bookings.api.spec.ts — "should validate required fields" (line 15)
Found existing API helpers that can be reused:
1. tests/api/helpers/bookings.api.ts — BookingsApi
Should I extend the existing test file or create a new one?
Which existing helpers should I reuse?
- Wait for user response. Note which helpers to reuse and proceed.
Phase 5: Test Plan
Present a concrete plan for approval before writing code.
## Test Plan: <description>
### Files
- Test file: `tests/api/<feature>.api.spec.ts`
- API helper: `tests/api/helpers/<resource>.api.ts` (new / reuse existing)
- Fixtures: `tests/api/fixtures.ts` (new / reuse existing)
### API Helper
- `<ResourceApi>` class wrapping <endpoints>
- Methods: create(), getById(), list(), update(), delete()
### Test Cases (grouped by category)
**describe('POST /api/bookings — validation')**
1. `should return 400 when body is empty` — POST {} → 400
2. `should return 400 when name is missing` — POST { date } → 400
...
**describe('POST /api/bookings — auth edge cases')**
8. `should return 401 without auth token` — POST (no auth) → 401
...
### Auth Strategy
- <detected pattern from Phase 0>
### Data Prerequisites
- <any setup/teardown needed>
### Environment
- Base URL: from playwright.config.ts
Wait for user approval before writing code.
Phase 6: Generate
6a. Create or update API helpers
- Follow the patterns in references/api-helper-pattern.md.
- Place new helpers in the project's established helper directory (discovered in Phase 0) or
tests/api/helpers/.
- For existing helpers: add new methods only — do NOT modify existing methods.
- Create or update the fixtures file to wire helpers into tests.
6b. Create the test file
- Follow the patterns in references/api-test-conventions.md.
- Use
test.describe to group tests by corner case category.
- Each
test() must be independent and isolated.
- Use descriptive test names that read as specifications.
- Follow the AAA pattern: Arrange → Act → Assert.
- For corner cases that require intentionally invalid data (wrong types, malformed JSON), bypass the API helper and use
request directly — helpers enforce correct types.
- Use API helpers for setup/teardown (creating prerequisite data).
After generating all files, you MUST proceed to Phase 7. Do not stop here.
Phase 7: Run Tests (MANDATORY — do NOT skip this phase)
This phase is required after every test creation or edit. You MUST execute it.
- Present the generated/modified files to the user.
- Ask the user: "Would you like me to run the tests now?" — You MUST ask this question. Do not end the workflow without asking.
- If the user says yes:
- Run
npx playwright test <test-file> --reporter=list
- If tests fail: diagnose using error output, fix, and re-run.
- Present pass/fail results to the user.
- If the user says no: acknowledge and end.
IMPORTANT: Never finish the skill without completing this phase. If you created or modified any test file, you MUST ask the user whether to run tests before ending.
Important Notes
- This skill creates API tests, not Playwright project scaffolding. The project must already have
@playwright/test installed.
- Never hardcode environment URLs. Always use
baseURL from Playwright config with relative URL paths.
- Always check existing API helpers before creating new ones. Reuse over duplication.
- API tests use
APIRequestContext — no browser, no page objects, no selectors.
- When authentication is needed, detect the project's existing auth pattern and follow it.
- Always ask the user whether to run tests after creating or modifying test files. This is the final required step of every invocation.
Reference Files
- references/api-test-conventions.md — APIRequestContext usage, test file structure, assertions, auth patterns, environment parameterization, general testing principles
- references/api-helper-pattern.md — API helper class structure, method naming, fixture integration, composition, anti-patterns
- references/corner-case-catalog.md — Systematic catalog of 13 corner case categories with reusable example patterns
1---2name: playwright-api3description: Use when the user wants to generate Playwright API-level corner case tests. Accepts an existing E2E test file or a free-form description, discovers API endpoints, then systematically generates corner case tests using APIRequestContext. No browser interaction.4---56# Playwright API Corner Case Test Generator78Generate comprehensive API corner case tests using Playwright's `APIRequestContext`. Systematically discover endpoints, then produce tests from a structured corner case catalog.910**Usage:** `/playwright-api <test-file-path or description>`1112The argument is either:13- A **path to an existing Playwright E2E test** — the skill reads it, runs it to capture network traffic, analyzes which APIs it exercises, and generates corner case tests for those endpoints.14- A **free-form description** of the API endpoints to test (e.g., `Corner cases for the booking CRUD API`, `Test edge cases on POST /api/users`).1516## Hard Rules1718- **Every invocation MUST end by asking the user whether to run the tests.** No exceptions.19- Never hardcode base URLs in tests or API helpers.20- Always check existing API tests and helpers before creating new ones.21- Never mock API responses — tests hit real endpoints.22- Always present the discovered API map for user confirmation before generating corner cases.23- Always present the corner case list for user selection before generating test code.24- Never guess at API schemas — discover from code, specs, traces, or ask the user.2526## Workflow2728### Phase 0: Project Discovery2930Automatically scan the project before any user interaction.31321. Parse `$ARGUMENTS` to determine input type:33 - If the argument is a file path that exists on disk and ends in `.spec.ts` or `.test.ts` → **test file mode** (Branch A).34 - Otherwise → **description mode** (Branch B).352. Search for Playwright configuration:36 - Look for `playwright.config.ts`, `playwright.config.js`37 - Check `package.json` for `@playwright/test` dependency383. **If Playwright is not installed**, inform the user and stop:39 > "This project does not have Playwright configured. Run `npm init playwright@latest` to set it up, then re-invoke this skill."404. Read the Playwright config and extract:41 - `baseURL` configuration42 - Test directory location (`testDir`)43 - `globalSetup` / `storageState` (for auth pattern detection)44 - Custom fixtures455. Scan for existing **API tests and helpers**:46 - Glob: `**/*.api.spec.ts`, `**/*.api.test.ts`47 - Glob: `**/api-helpers/**`, `**/helpers/*.api.ts`48 - Record: file path, describe block names, test names, helper class names496. Scan for **API route definitions** in source code:50 - Glob: `**/routes/**`, `**/controllers/**`, `**/*.controller.ts`, `**/*.routes.ts`51 - Look for Express routers, NestJS controllers, FastAPI routes, or similar527. Scan for **API specifications**:53 - Glob: `**/openapi.*`, `**/swagger.*`, `**/*.openapi.yaml`, `**/*.openapi.json`548. Scan for **DTOs and type definitions**:55 - Glob: `**/dto/**`, `**/schemas/**`, `**/models/**`, `**/types/**`569. Detect **auth pattern**: check for `storageState` in config, `globalSetup` files, `extraHTTPHeaders`, Bearer token patterns in existing tests.5758### Phase 1: Input Analysis5960#### Branch A — Test file61621. Read the E2E test file.632. Read all imported Page Object Models, helpers, and fixtures.643. Summarize what user flow the E2E test exercises.654. Extract API-related patterns from the code:66 - `waitForResponse` / `waitForRequest` calls → endpoint URLs and methods67 - `page.route()` / `page.on('request')` → intercepted endpoints68 - URL string literals matching API patterns (`/api/`, `/v1/`, etc.)69 - `fetch()` calls in evaluated scripts705. Present the initial summary:71 > "This E2E test exercises the booking creation flow. I found these API calls in the code: POST /api/bookings, GET /api/bookings/{id}. I'll run the test next to discover any additional endpoints."7273#### Branch B — Description74751. Analyze the description together with project context from Phase 0.762. Ask the user **3-5 focused questions**, selected based on what is unclear:77 - Which specific API endpoints are involved? (list any you know)78 - What HTTP methods and resource types? (REST CRUD, RPC, GraphQL?)79 - What authentication is required?80 - Are there request/response schemas, DTOs, or type definitions available?81 - What does "success" look like for the happy path?823. **Wait for answers before proceeding.**8384### Phase 2: API Discovery8586**Both branches: ask about API specifications first.**8788> "Do you have an API specification (OpenAPI/Swagger, Postman collection, or similar) for these endpoints? If so, where is it?"8990If the user provides a spec, read and parse it to extract:91- Endpoints (method + path)92- Request schemas (required/optional fields, types, constraints like maxLength, enum, pattern)93- Response schemas per status code94- Authentication requirements9596This spec becomes the **primary source of truth** for corner case generation — it reveals constraints that code analysis alone may miss.9798#### Branch A — Test file (trace-based discovery)991001. Run the E2E test with trace capture:101 ```102 npx playwright test <file> --trace on --reporter=list103 ```1042. If the test **passes**: parse the trace to extract all HTTP requests:105 - HTTP method and URL path106 - Request headers and body shape107 - Response status code and body shape108 - Build the API endpoint map1093. If the test **fails or cannot run**: inform the user and fall back to the code-only analysis from Phase 1.1104. Merge code-analysis endpoints with trace-discovered endpoints.1115. Cross-reference with the API spec (if provided) to fill in schema details, constraints, and additional endpoints not exercised by the E2E test.112113#### Branch B — Description (code-based discovery)1141151. Search source code for route definitions matching the described endpoints.1162. Read DTOs/interfaces for request/response shapes.1173. Cross-reference with the API spec (if provided) for complete schema details.118119#### Both branches converge120121Present the **API Endpoint Map** to the user:122123```124## Discovered API Endpoints125126| # | Method | Path | Request Body | Success Status | Key Constraints |127|---|--------|-------------------|----------------------|----------------|-----------------------|128| 1 | POST | /api/bookings | { name*, date* } | 201 | name: maxLen 100 |129| 2 | GET | /api/bookings/:id | — | 200 | id: positive integer |130| 3 | GET | /api/bookings | — | 200 | paginated, filterable |131132* = required field133Auth: Bearer token via storageState134Base URL: from playwright.config.ts135136Is this complete? Any endpoints to add or remove?137```138139**Wait for user confirmation before proceeding.**140141### Phase 3: Corner Case Analysis1421431. Load [references/corner-case-catalog.md](references/corner-case-catalog.md).1442. For each confirmed endpoint, walk through every category in the catalog:145 - Check the **Applies to** tag — skip categories that don't match.146 - Generate concrete test case ideas using the endpoint's actual fields and types.1473. If an API spec was provided, use its constraints to generate **more targeted** corner cases:148 - Field has `maxLength: 100` → test lengths 100 (valid), 101 (invalid), and 0 (empty).149 - Field is an enum → test a value not in the enum.150 - Field has a regex pattern → test a string that violates the pattern.151 - Field has min/max range → test at boundaries and beyond.1524. Present the full list grouped by endpoint with category tags:153154```155## Corner Cases for POST /api/bookings156157### Validation — Required Fields1581. Empty request body → expect 4001592. Missing "name" → expect 4001603. Missing "date" → expect 4001614. Null for "name" → expect 400162163### Validation — Boundary Values1645. Name at max length (100 chars) → expect 2011656. Name exceeding max length (101 chars) → expect 4001667. Empty string for "name" → expect 400167168### Auth Edge Cases1698. No auth token → expect 4011709. Expired token → expect 401171...172173## Corner Cases for GET /api/bookings/:id174175### Resource Not Found17610. Non-existent ID → expect 40417711. Non-numeric ID → expect 400178...179180Select which corner cases to implement (e.g., "all", "1-9", "skip auth cases"):181```182183**Wait for user selection.**184185### Phase 4: Similarity Search186187Avoid duplicating existing tests. Find reusable code.1881891. Search existing API test files for overlapping endpoint coverage:190 - URL/route overlap with discovered endpoints191 - Keyword matching against `test.describe` and `test()` names1922. Search existing API helpers for reusable client classes.1933. **If overlap is found**, present it:194 ```195 Found existing API tests that may overlap:196 1. tests/api/bookings.api.spec.ts — "should validate required fields" (line 15)197198 Found existing API helpers that can be reused:199 1. tests/api/helpers/bookings.api.ts — BookingsApi200201 Should I extend the existing test file or create a new one?202 Which existing helpers should I reuse?203 ```2044. **Wait for user response.** Note which helpers to reuse and proceed.205206### Phase 5: Test Plan207208Present a concrete plan for approval before writing code.209210```markdown211## Test Plan: <description>212213### Files214- Test file: `tests/api/<feature>.api.spec.ts`215- API helper: `tests/api/helpers/<resource>.api.ts` (new / reuse existing)216- Fixtures: `tests/api/fixtures.ts` (new / reuse existing)217218### API Helper219- `<ResourceApi>` class wrapping <endpoints>220- Methods: create(), getById(), list(), update(), delete()221222### Test Cases (grouped by category)223**describe('POST /api/bookings — validation')**2241. `should return 400 when body is empty` — POST {} → 4002252. `should return 400 when name is missing` — POST { date } → 400226...227228**describe('POST /api/bookings — auth edge cases')**2298. `should return 401 without auth token` — POST (no auth) → 401230...231232### Auth Strategy233- <detected pattern from Phase 0>234235### Data Prerequisites236- <any setup/teardown needed>237238### Environment239- Base URL: from playwright.config.ts240```241242**Wait for user approval before writing code.**243244### Phase 6: Generate245246#### 6a. Create or update API helpers247248- Follow the patterns in [references/api-helper-pattern.md](references/api-helper-pattern.md).249- Place new helpers in the project's established helper directory (discovered in Phase 0) or `tests/api/helpers/`.250- For existing helpers: add new methods only — do NOT modify existing methods.251- Create or update the fixtures file to wire helpers into tests.252253#### 6b. Create the test file254255- Follow the patterns in [references/api-test-conventions.md](references/api-test-conventions.md).256- Use `test.describe` to group tests by corner case category.257- Each `test()` must be independent and isolated.258- Use descriptive test names that read as specifications.259- Follow the AAA pattern: Arrange → Act → Assert.260- For corner cases that require intentionally invalid data (wrong types, malformed JSON), bypass the API helper and use `request` directly — helpers enforce correct types.261- Use API helpers for setup/teardown (creating prerequisite data).262263**After generating all files, you MUST proceed to Phase 7. Do not stop here.**264265### Phase 7: Run Tests (MANDATORY — do NOT skip this phase)266267**This phase is required after every test creation or edit. You MUST execute it.**2682691. Present the generated/modified files to the user.2702. **Ask the user: "Would you like me to run the tests now?"** — You MUST ask this question. Do not end the workflow without asking.2713. If the user says **yes**:272 - Run `npx playwright test <test-file> --reporter=list`273 - If tests fail: diagnose using error output, fix, and re-run.274 - Present pass/fail results to the user.2754. If the user says **no**: acknowledge and end.276277**IMPORTANT:** Never finish the skill without completing this phase. If you created or modified any test file, you MUST ask the user whether to run tests before ending.278279## Important Notes280281- This skill creates API tests, not Playwright project scaffolding. The project must already have `@playwright/test` installed.282- Never hardcode environment URLs. Always use `baseURL` from Playwright config with relative URL paths.283- Always check existing API helpers before creating new ones. Reuse over duplication.284- API tests use `APIRequestContext` — no browser, no page objects, no selectors.285- When authentication is needed, detect the project's existing auth pattern and follow it.286- **Always ask the user whether to run tests after creating or modifying test files.** This is the final required step of every invocation.287288## Reference Files289290- **[references/api-test-conventions.md](references/api-test-conventions.md)** — APIRequestContext usage, test file structure, assertions, auth patterns, environment parameterization, general testing principles291- **[references/api-helper-pattern.md](references/api-helper-pattern.md)** — API helper class structure, method naming, fixture integration, composition, anti-patterns292- **[references/corner-case-catalog.md](references/corner-case-catalog.md)** — Systematic catalog of 13 corner case categories with reusable example patterns