.agents/skills/playwright-best-practices/architecture/test-architecture.md
When to use: Deciding which test type to write for a feature. Ask: "What's the cheapest test that gives confidence this works?"
| Scenario | Recommended Type | Rationale |
|---|---|---|
| Login / auth flow | E2E | Cross-page, cookies, redirects, session state |
| Form submission | Component | Isolated validation logic, error states |
| CRUD operations | API | Data integrity matters more than UI |
| Search with results UI | Component + API | API for query logic; component for rendering |
| Cross-page navigation | E2E | Routing, history, deep linking |
| API error handling | API | Status codes, error shapes, edge cases |
| UI error feedback | Component | Toast, banner, inline error rendering |
| Accessibility | Component | ARIA roles, keyboard nav per-component |
| Responsive layout | Component | Viewport-specific rendering without full app |
| API contract validation | API | Response shapes, headers, auth |
| WebSocket/real-time | E2E | Requires full browser environment |
| Payment / checkout | E2E | Multi-step, third-party iframes |
| Onboarding wizard | E2E | Multi-step, state persists across pages |
| Widget behavior | Component | Toggle, accordion, date picker, modal |
| Permissions / authorization | API | Role-based access is backend logic |
Ideal for:
Avoid for:
import {test, expect} from '@playwright/test'
test.describe('Products API', () => {
let token: string
test.beforeAll(async ({request}) => {
const res = await request.post('/api/auth/token', {
data: {email: '[email protected]', password: 'mgr-secret'},
})
token = (await res.json()).accessToken
})
test('creates product with valid payload', async ({request}) => {
const res = await request.post('/api/products', {
headers: {Authorization: `Bearer ${token}`},
data: {name: 'Widget Pro', sku: 'WGT-100', price: 29.99},
})
expect(res.status()).toBe(201)
const product = await res.json()
expect(product).toMatchObject({name: 'Widget Pro', sku: 'WGT-100'})
expect(product).toHaveProperty('id')
})
test('rejects duplicate SKU with 409', async ({request}) => {
const res = await request.post('/api/products', {
headers: {Authorization: `Bearer ${token}`},
data: {name: 'Duplicate', sku: 'WGT-100', price: 19.99},
})
expect(res.status()).toBe(409)
expect((await res.json()).message).toContain('already exists')
})
test('returns 422 for missing required fields', async ({request}) => {
const res = await request.post('/api/products', {
headers: {Authorization: `Bearer ${token}`},
data: {name: 'Incomplete'},
})
expect(res.status()).toBe(422)
const err = await res.json()
expect(err.errors).toContainEqual(expect.objectContaining({field: 'sku'}))
})
test('staff role cannot delete products', async ({request}) => {
const staffLogin = await request.post('/api/auth/token', {
data: {email: '[email protected]', password: 'staff-pass'},
})
const staffToken = (await staffLogin.json()).accessToken
const res = await request.delete('/api/products/123', {
headers: {Authorization: `Bearer ${staffToken}`},
})
expect(res.status()).toBe(403)
})
test('lists products with pagination', async ({request}) => {
const res = await request.get('/api/products', {
headers: {Authorization: `Bearer ${token}`},
params: {page: '1', limit: '20'},
})
expect(res.status()).toBe(200)
const body = await res.json()
expect(body.items).toBeInstanceOf(Array)
expect(body.items.length).toBeLessThanOrEqual(20)
expect(body).toHaveProperty('totalCount')
})
})
Ideal for:
Avoid for:
import { test, expect } from "@playwright/experimental-ct-react";
import { ContactForm } from "../src/components/ContactForm";
test.describe("ContactForm component", () => {
test("displays validation errors on empty submit", async ({ mount }) => {
const component = await mount(<ContactForm onSubmit={() => {}} />);
await component.getByRole("button", { name: "Send message" }).click();
await expect(component.getByText("Name is required")).toBeVisible();
await expect(component.getByText("Email is required")).toBeVisible();
});
test("rejects malformed email", async ({ mount }) => {
const component = await mount(<ContactForm onSubmit={() => {}} />);
await component.getByLabel("Name").fill("Alex");
await component.getByLabel("Email").fill("invalid-email");
await component.getByLabel("Message").fill("Hello");
await component.getByRole("button", { name: "Send message" }).click();
await expect(component.getByText("Enter a valid email")).toBeVisible();
});
test("invokes onSubmit with form data", async ({ mount }) => {
const submissions: Array<{ name: string; email: string; message: string }> =
[];
const component = await mount(
<ContactForm onSubmit={(data) => submissions.push(data)} />
);
await component.getByLabel("Name").fill("Alex");
await component.getByLabel("Email").fill("[email protected]");
await component.getByLabel("Message").fill("Inquiry about pricing");
await component.getByRole("button", { name: "Send message" }).click();
expect(submissions).toHaveLength(1);
expect(submissions[0]).toEqual({
name: "Alex",
email: "[email protected]",
message: "Inquiry about pricing",
});
});
test("disables button during submission", async ({ mount }) => {
const component = await mount(
<ContactForm onSubmit={() => {}} submitting={true} />
);
await expect(
component.getByRole("button", { name: "Sending..." })
).toBeDisabled();
});
test("associates labels with inputs for accessibility", async ({ mount }) => {
const component = await mount(<ContactForm onSubmit={() => {}} />);
await expect(
component.getByRole("textbox", { name: "Name" })
).toBeVisible();
await expect(
component.getByRole("textbox", { name: "Email" })
).toBeVisible();
});
});
Ideal for:
Avoid for:
import {test, expect} from '@playwright/test'
test.describe('subscription flow', () => {
test.beforeEach(async ({page}) => {
await page.request.post('/api/test/seed-account', {
data: {plan: 'free', email: '[email protected]'},
})
await page.goto('/account/upgrade')
})
test('upgrades to premium plan', async ({page}) => {
await test.step('select plan', async () => {
await expect(page.getByRole('heading', {name: 'Choose Your Plan'})).toBeVisible()
await page.getByRole('button', {name: 'Select Premium'}).click()
})
await test.step('enter billing details', async () => {
await page.getByLabel('Cardholder name').fill('Sam Johnson')
await page.getByLabel('Billing address').fill('456 Oak Ave')
await page.getByLabel('City').fill('Seattle')
await page.getByRole('combobox', {name: 'State'}).selectOption('WA')
await page.getByLabel('Postal code').fill('98101')
await page.getByRole('button', {name: 'Continue'}).click()
})
await test.step('complete payment', async () => {
const paymentFrame = page.frameLocator('iframe[title="Secure Payment"]')
await paymentFrame.getByLabel('Card number').fill('5555555555554444')
await paymentFrame.getByLabel('Expiry').fill('09/29')
await paymentFrame.getByLabel('CVV').fill('456')
await page.getByRole('button', {name: 'Subscribe now'}).click()
})
await test.step('verify success', async () => {
await page.waitForURL('**/account/subscription/success**')
await expect(page.getByRole('heading', {name: 'Welcome to Premium'})).toBeVisible()
await expect(page.getByText(/Subscription #\d+/)).toBeVisible()
})
})
})
Effective test suites combine all three types. Example for an "inventory management" feature:
Cover every backend logic permutation. Cheap to run and maintain.
tests/api/inventory.spec.ts
- creates item with valid data (201)
- rejects duplicate SKU (409)
- rejects invalid quantity format (422)
- rejects missing required fields (422)
- warehouse-staff cannot delete items (403)
- unauthenticated request returns 401
- lists items with pagination
- filters items by category
- updates item stock level
- archives an item
- prevents archiving items with pending orders
Cover every visual state and interaction.
tests/components/InventoryForm.spec.tsx
- shows validation errors on empty submit
- shows inline error for invalid SKU format
- disables submit while saving
- calls onSubmit with form data
- resets form after successful save
tests/components/InventoryTable.spec.tsx
- renders item rows from props
- shows empty state when no items
- handles archive confirmation modal
- sorts by column header click
- shows stock level badges with correct colors
Cover only critical paths proving full stack works.
tests/e2e/inventory.spec.ts
- manager creates item and sees it in list
- manager updates item stock level
- warehouse-staff cannot access admin settings
For this feature:
Total: 24 tests, ~22 seconds. API tests catch most regressions. Component tests catch UI bugs. E2E tests prove wiring works. If E2E fails but API and component pass, the problem is in integration (routing, state management, API client).
| Anti-Pattern | Problem | Better Approach |
|---|---|---|
| E2E for every validation rule | 30-second browser test for something API covers in 200ms | API test for validation, one component test for error display |
| No API tests, all E2E | Slow suite, flaky from UI timing, hard to diagnose | API tests for data/logic, E2E for critical paths only |
| Component tests mocking everything | Tests pass but app broken because mocks drift | Mock only external boundaries; API tests verify real contracts |
| Same assertion in API, component, AND E2E | Triple maintenance cost | Each layer tests what it uniquely verifies |
| E2E creating test data via UI | 2-minute test where 90 seconds is setup | Seed via API in beforeEach, test actual flow |
| Testing third-party behavior | Testing that Stripe validates cards (Stripe's job) | Mock Stripe; trust their contract |
| Skipping API layer | Can't tell if bug is frontend or backend | API tests isolate backend; component tests isolate frontend |
| One giant E2E for entire feature | 5-minute test failing somewhere with no clear cause | Focused E2E per critical path; use test.step() |
request API for HTTP testingstorageState