[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWC4AE11BFV3Q0Q2K8CWJ1":3,"skill-same:01M7BWC4AE11BFV3Q0Q2K8CWJ1":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWC4AE11BFV3Q0Q2K8CWJ1","e2e-testing-patterns",null,"Master end-to-end testing with Playwright and Cypress to build reliable test suites that catch bugs, improve confidence, and enable fast deployment. Use when implementing E2E tests, debugging flaky tests, or establishing testing standards.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Fe2e-testing-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: e2e-testing-patterns\ndescription: Master end-to-end testing with Playwright and Cypress to build reliable test suites that catch bugs, improve confidence, and enable fast deployment. Use when implementing E2E tests, debugging flaky tests, or establishing testing standards.\n---\n\n# E2E Testing Patterns\n\nBuild reliable, fast, and maintainable end-to-end test suites that provide confidence to ship code quickly and catch regressions before users do.\n\n## When to Use This Skill\n\n- Implementing end-to-end test automation\n- Debugging flaky or unreliable tests\n- Testing critical user workflows\n- Setting up CI\u002FCD test pipelines\n- Testing across multiple browsers\n- Validating accessibility requirements\n- Testing responsive designs\n- Establishing E2E testing standards\n\n## Core Concepts\n\n### 1. E2E Testing Fundamentals\n\n**What to Test with E2E:**\n\n- Critical user journeys (login, checkout, signup)\n- Complex interactions (drag-and-drop, multi-step forms)\n- Cross-browser compatibility\n- Real API integration\n- Authentication flows\n\n**What NOT to Test with E2E:**\n\n- Unit-level logic (use unit tests)\n- API contracts (use integration tests)\n- Edge cases (too slow)\n- Internal implementation details\n\n### 2. Test Philosophy\n\n**The Testing Pyramid:**\n\n```\n        \u002F\\\n       \u002FE2E\\         ← Few, focused on critical paths\n      \u002F─────\\\n     \u002FIntegr\\        ← More, test component interactions\n    \u002F────────\\\n   \u002FUnit Tests\\      ← Many, fast, isolated\n  \u002F────────────\\\n```\n\n**Best Practices:**\n\n- Test user behavior, not implementation\n- Keep tests independent\n- Make tests deterministic\n- Optimize for speed\n- Use data-testid, not CSS selectors\n\n## Playwright Patterns\n\n### Setup and Configuration\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from \"@playwright\u002Ftest\";\n\nexport default defineConfig({\n  testDir: \".\u002Fe2e\",\n  timeout: 30000,\n  expect: {\n    timeout: 5000,\n  },\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: [[\"html\"], [\"junit\", { outputFile: \"results.xml\" }]],\n  use: {\n    baseURL: \"http:\u002F\u002Flocalhost:3000\",\n    trace: \"on-first-retry\",\n    screenshot: \"only-on-failure\",\n    video: \"retain-on-failure\",\n  },\n  projects: [\n    { name: \"chromium\", use: { ...devices[\"Desktop Chrome\"] } },\n    { name: \"firefox\", use: { ...devices[\"Desktop Firefox\"] } },\n    { name: \"webkit\", use: { ...devices[\"Desktop Safari\"] } },\n    { name: \"mobile\", use: { ...devices[\"iPhone 13\"] } },\n  ],\n});\n```\n\n### Pattern 1: Page Object Model\n\n```typescript\n\u002F\u002F pages\u002FLoginPage.ts\nimport { Page, Locator } from \"@playwright\u002Ftest\";\n\nexport class LoginPage {\n  readonly page: Page;\n  readonly emailInput: Locator;\n  readonly passwordInput: Locator;\n  readonly loginButton: Locator;\n  readonly errorMessage: Locator;\n\n  constructor(page: Page) {\n    this.page = page;\n    this.emailInput = page.getByLabel(\"Email\");\n    this.passwordInput = page.getByLabel(\"Password\");\n    this.loginButton = page.getByRole(\"button\", { name: \"Login\" });\n    this.errorMessage = page.getByRole(\"alert\");\n  }\n\n  async goto() {\n    await this.page.goto(\"\u002Flogin\");\n  }\n\n  async login(email: string, password: string) {\n    await this.emailInput.fill(email);\n    await this.passwordInput.fill(password);\n    await this.loginButton.click();\n  }\n\n  async getErrorMessage(): Promise\u003Cstring> {\n    return (await this.errorMessage.textContent()) ?? \"\";\n  }\n}\n\n\u002F\u002F Test using Page Object\nimport { test, expect } from \"@playwright\u002Ftest\";\nimport { LoginPage } from \".\u002Fpages\u002FLoginPage\";\n\ntest(\"successful login\", async ({ page }) => {\n  const loginPage = new LoginPage(page);\n  await loginPage.goto();\n  await loginPage.login(\"user@example.com\", \"password123\");\n\n  await expect(page).toHaveURL(\"\u002Fdashboard\");\n  await expect(page.getByRole(\"heading\", { name: \"Dashboard\" })).toBeVisible();\n});\n\ntest(\"failed login shows error\", async ({ page }) => {\n  const loginPage = new LoginPage(page);\n  await loginPage.goto();\n  await loginPage.login(\"invalid@example.com\", \"wrong\");\n\n  const error = await loginPage.getErrorMessage();\n  expect(error).toContain(\"Invalid credentials\");\n});\n```\n\n### Pattern 2: Fixtures for Test Data\n\n```typescript\n\u002F\u002F fixtures\u002Ftest-data.ts\nimport { test as base } from \"@playwright\u002Ftest\";\n\ntype TestData = {\n  testUser: {\n    email: string;\n    password: string;\n    name: string;\n  };\n  adminUser: {\n    email: string;\n    password: string;\n  };\n};\n\nexport const test = base.extend\u003CTestData>({\n  testUser: async ({}, use) => {\n    const user = {\n      email: `test-${Date.now()}@example.com`,\n      password: \"Test123!@#\",\n      name: \"Test User\",\n    };\n    \u002F\u002F Setup: Create user in database\n    await createTestUser(user);\n    await use(user);\n    \u002F\u002F Teardown: Clean up user\n    await deleteTestUser(user.email);\n  },\n\n  adminUser: async ({}, use) => {\n    await use({\n      email: \"admin@example.com\",\n      password: process.env.ADMIN_PASSWORD!,\n    });\n  },\n});\n\n\u002F\u002F Usage in tests\nimport { test } from \".\u002Ffixtures\u002Ftest-data\";\n\ntest(\"user can update profile\", async ({ page, testUser }) => {\n  await page.goto(\"\u002Flogin\");\n  await page.getByLabel(\"Email\").fill(testUser.email);\n  await page.getByLabel(\"Password\").fill(testUser.password);\n  await page.getByRole(\"button\", { name: \"Login\" }).click();\n\n  await page.goto(\"\u002Fprofile\");\n  await page.getByLabel(\"Name\").fill(\"Updated Name\");\n  await page.getByRole(\"button\", { name: \"Save\" }).click();\n\n  await expect(page.getByText(\"Profile updated\")).toBeVisible();\n});\n```\n\n### Pattern 3: Waiting Strategies\n\n```typescript\n\u002F\u002F ❌ Bad: Fixed timeouts\nawait page.waitForTimeout(3000); \u002F\u002F Flaky!\n\n\u002F\u002F ✅ Good: Wait for specific conditions\nawait page.waitForLoadState(\"networkidle\");\nawait page.waitForURL(\"\u002Fdashboard\");\nawait page.waitForSelector('[data-testid=\"user-profile\"]');\n\n\u002F\u002F ✅ Better: Auto-waiting with assertions\nawait expect(page.getByText(\"Welcome\")).toBeVisible();\nawait expect(page.getByRole(\"button\", { name: \"Submit\" })).toBeEnabled();\n\n\u002F\u002F Wait for API response\nconst responsePromise = page.waitForResponse(\n  (response) =>\n    response.url().includes(\"\u002Fapi\u002Fusers\") && response.status() === 200,\n);\nawait page.getByRole(\"button\", { name: \"Load Users\" }).click();\nconst response = await responsePromise;\nconst data = await response.json();\nexpect(data.users).toHaveLength(10);\n\n\u002F\u002F Wait for multiple conditions\nawait Promise.all([\n  page.waitForURL(\"\u002Fsuccess\"),\n  page.waitForLoadState(\"networkidle\"),\n  expect(page.getByText(\"Payment successful\")).toBeVisible(),\n]);\n```\n\n### Pattern 4: Network Mocking and Interception\n\n```typescript\n\u002F\u002F Mock API responses\ntest(\"displays error when API fails\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fusers\", (route) => {\n    route.fulfill({\n      status: 500,\n      contentType: \"application\u002Fjson\",\n      body: JSON.stringify({ error: \"Internal Server Error\" }),\n    });\n  });\n\n  await page.goto(\"\u002Fusers\");\n  await expect(page.getByText(\"Failed to load users\")).toBeVisible();\n});\n\n\u002F\u002F Intercept and modify requests\ntest(\"can modify API request\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fusers\", async (route) => {\n    const request = route.request();\n    const postData = JSON.parse(request.postData() || \"{}\");\n\n    \u002F\u002F Modify request\n    postData.role = \"admin\";\n\n    await route.continue({\n      postData: JSON.stringify(postData),\n    });\n  });\n\n  \u002F\u002F Test continues...\n});\n\n\u002F\u002F Mock third-party services\ntest(\"payment flow with mocked Stripe\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fstripe\u002F**\", (route) => {\n    route.fulfill({\n      status: 200,\n      body: JSON.stringify({\n        id: \"mock_payment_id\",\n        status: \"succeeded\",\n      }),\n    });\n  });\n\n  \u002F\u002F Test payment flow with mocked response\n});\n```\n\n## Cypress Patterns\n\n### Setup and Configuration\n\n```typescript\n\u002F\u002F cypress.config.ts\nimport { defineConfig } from \"cypress\";\n\nexport default defineConfig({\n  e2e: {\n    baseUrl: \"http:\u002F\u002Flocalhost:3000\",\n    viewportWidth: 1280,\n    viewportHeight: 720,\n    video: false,\n    screenshotOnRunFailure: true,\n    defaultCommandTimeout: 10000,\n    requestTimeout: 10000,\n    setupNodeEvents(on, config) {\n      \u002F\u002F Implement node event listeners\n    },\n  },\n});\n```\n\n### Pattern 1: Custom Commands\n\n```typescript\n\u002F\u002F cypress\u002Fsupport\u002Fcommands.ts\ndeclare global {\n  namespace Cypress {\n    interface Chainable {\n      login(email: string, password: string): Chainable\u003Cvoid>;\n      createUser(userData: UserData): Chainable\u003CUser>;\n      dataCy(value: string): Chainable\u003CJQuery\u003CHTMLElement>>;\n    }\n  }\n}\n\nCypress.Commands.add(\"login\", (email: string, password: string) => {\n  cy.visit(\"\u002Flogin\");\n  cy.get('[data-testid=\"email\"]').type(email);\n  cy.get('[data-testid=\"password\"]').type(password);\n  cy.get('[data-testid=\"login-button\"]').click();\n  cy.url().should(\"include\", \"\u002Fdashboard\");\n});\n\nCypress.Commands.add(\"createUser\", (userData: UserData) => {\n  return cy.request(\"POST\", \"\u002Fapi\u002Fusers\", userData).its(\"body\");\n});\n\nCypress.Commands.add(\"dataCy\", (value: string) => {\n  return cy.get(`[data-cy=\"${value}\"]`);\n});\n\n\u002F\u002F Usage\ncy.login(\"user@example.com\", \"password\");\ncy.dataCy(\"submit-button\").click();\n```\n\n### Pattern 2: Cypress Intercept\n\n```typescript\n\u002F\u002F Mock API calls\ncy.intercept(\"GET\", \"\u002Fapi\u002Fusers\", {\n  statusCode: 200,\n  body: [\n    { id: 1, name: \"John\" },\n    { id: 2, name: \"Jane\" },\n  ],\n}).as(\"getUsers\");\n\ncy.visit(\"\u002Fusers\");\ncy.wait(\"@getUsers\");\ncy.get('[data-testid=\"user-list\"]').children().should(\"have.length\", 2);\n\n\u002F\u002F Modify responses\ncy.intercept(\"GET\", \"\u002Fapi\u002Fusers\", (req) => {\n  req.reply((res) => {\n    \u002F\u002F Modify response\n    res.body.users = res.body.users.slice(0, 5);\n    res.send();\n  });\n});\n\n\u002F\u002F Simulate slow network\ncy.intercept(\"GET\", \"\u002Fapi\u002Fdata\", (req) => {\n  req.reply((res) => {\n    res.delay(3000); \u002F\u002F 3 second delay\n    res.send();\n  });\n});\n```\n\n## Advanced Patterns\n\n### Pattern 1: Visual Regression Testing\n\n```typescript\n\u002F\u002F With Playwright\nimport { test, expect } from \"@playwright\u002Ftest\";\n\ntest(\"homepage looks correct\", async ({ page }) => {\n  await page.goto(\"\u002F\");\n  await expect(page).toHaveScreenshot(\"homepage.png\", {\n    fullPage: true,\n    maxDiffPixels: 100,\n  });\n});\n\ntest(\"button in all states\", async ({ page }) => {\n  await page.goto(\"\u002Fcomponents\");\n\n  const button = page.getByRole(\"button\", { name: \"Submit\" });\n\n  \u002F\u002F Default state\n  await expect(button).toHaveScreenshot(\"button-default.png\");\n\n  \u002F\u002F Hover state\n  await button.hover();\n  await expect(button).toHaveScreenshot(\"button-hover.png\");\n\n  \u002F\u002F Disabled state\n  await button.evaluate((el) => el.setAttribute(\"disabled\", \"true\"));\n  await expect(button).toHaveScreenshot(\"button-disabled.png\");\n});\n```\n\n### Pattern 2: Parallel Testing with Sharding\n\n```typescript\n\u002F\u002F playwright.config.ts\nexport default defineConfig({\n  projects: [\n    {\n      name: \"shard-1\",\n      use: { ...devices[\"Desktop Chrome\"] },\n      grepInvert: \u002F@slow\u002F,\n      shard: { current: 1, total: 4 },\n    },\n    {\n      name: \"shard-2\",\n      use: { ...devices[\"Desktop Chrome\"] },\n      shard: { current: 2, total: 4 },\n    },\n    \u002F\u002F ... more shards\n  ],\n});\n\n\u002F\u002F Run in CI\n\u002F\u002F npx playwright test --shard=1\u002F4\n\u002F\u002F npx playwright test --shard=2\u002F4\n```\n\n### Pattern 3: Accessibility Testing\n\n```typescript\n\u002F\u002F Install: npm install @axe-core\u002Fplaywright\nimport { test, expect } from \"@playwright\u002Ftest\";\nimport AxeBuilder from \"@axe-core\u002Fplaywright\";\n\ntest(\"page should not have accessibility violations\", async ({ page }) => {\n  await page.goto(\"\u002F\");\n\n  const accessibilityScanResults = await new AxeBuilder({ page })\n    .exclude(\"#third-party-widget\")\n    .analyze();\n\n  expect(accessibilityScanResults.violations).toEqual([]);\n});\n\ntest(\"form is accessible\", async ({ page }) => {\n  await page.goto(\"\u002Fsignup\");\n\n  const results = await new AxeBuilder({ page }).include(\"form\").analyze();\n\n  expect(results.violations).toEqual([]);\n});\n```\n\n## Best Practices\n\n1. **Use Data Attributes**: `data-testid` or `data-cy` for stable selectors\n2. **Avoid Brittle Selectors**: Don't rely on CSS classes or DOM structure\n3. **Test User Behavior**: Click, type, see - not implementation details\n4. **Keep Tests Independent**: Each test should run in isolation\n5. **Clean Up Test Data**: Create and destroy test data in each test\n6. **Use Page Objects**: Encapsulate page logic\n7. **Meaningful Assertions**: Check actual user-visible behavior\n8. **Optimize for Speed**: Mock when possible, parallel execution\n\n```typescript\n\u002F\u002F ❌ Bad selectors\ncy.get(\".btn.btn-primary.submit-button\").click();\ncy.get(\"div > form > div:nth-child(2) > input\").type(\"text\");\n\n\u002F\u002F ✅ Good selectors\ncy.getByRole(\"button\", { name: \"Submit\" }).click();\ncy.getByLabel(\"Email address\").type(\"user@example.com\");\ncy.get('[data-testid=\"email-input\"]').type(\"user@example.com\");\n```\n\n## Common Pitfalls\n\n- **Flaky Tests**: Use proper waits, not fixed timeouts\n- **Slow Tests**: Mock external APIs, use parallel execution\n- **Over-Testing**: Don't test every edge case with E2E\n- **Coupled Tests**: Tests should not depend on each other\n- **Poor Selectors**: Avoid CSS classes and nth-child\n- **No Cleanup**: Clean up test data after each test\n- **Testing Implementation**: Test user behavior, not internals\n\n## Debugging Failing Tests\n\n```typescript\n\u002F\u002F Playwright debugging\n\u002F\u002F 1. Run in headed mode\nnpx playwright test --headed\n\n\u002F\u002F 2. Run in debug mode\nnpx playwright test --debug\n\n\u002F\u002F 3. Use trace viewer\nawait page.screenshot({ path: 'screenshot.png' });\nawait page.video()?.saveAs('video.webm');\n\n\u002F\u002F 4. Add test.step for better reporting\ntest('checkout flow', async ({ page }) => {\n    await test.step('Add item to cart', async () => {\n        await page.goto('\u002Fproducts');\n        await page.getByRole('button', { name: 'Add to Cart' }).click();\n    });\n\n    await test.step('Proceed to checkout', async () => {\n        await page.goto('\u002Fcart');\n        await page.getByRole('button', { name: 'Checkout' }).click();\n    });\n});\n\n\u002F\u002F 5. Inspect page state\nawait page.pause();  \u002F\u002F Pauses execution, opens inspector\n```\n","# E2E Testing Patterns\n\nBuild reliable, fast, and maintainable end-to-end test suites that provide confidence to ship code quickly and catch regressions before users do.\n\n## When to Use This Skill\n\n- Implementing end-to-end test automation\n- Debugging flaky or unreliable tests\n- Testing critical user workflows\n- Setting up CI\u002FCD test pipelines\n- Testing across multiple browsers\n- Validating accessibility requirements\n- Testing responsive designs\n- Establishing E2E testing standards\n\n## Core Concepts\n\n### 1. E2E Testing Fundamentals\n\n**What to Test with E2E:**\n\n- Critical user journeys (login, checkout, signup)\n- Complex interactions (drag-and-drop, multi-step forms)\n- Cross-browser compatibility\n- Real API integration\n- Authentication flows\n\n**What NOT to Test with E2E:**\n\n- Unit-level logic (use unit tests)\n- API contracts (use integration tests)\n- Edge cases (too slow)\n- Internal implementation details\n\n### 2. Test Philosophy\n\n**The Testing Pyramid:**\n\n```\n        \u002F\\\n       \u002FE2E\\         ← Few, focused on critical paths\n      \u002F─────\\\n     \u002FIntegr\\        ← More, test component interactions\n    \u002F────────\\\n   \u002FUnit Tests\\      ← Many, fast, isolated\n  \u002F────────────\\\n```\n\n**Best Practices:**\n\n- Test user behavior, not implementation\n- Keep tests independent\n- Make tests deterministic\n- Optimize for speed\n- Use data-testid, not CSS selectors\n\n## Playwright Patterns\n\n### Setup and Configuration\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from \"@playwright\u002Ftest\";\n\nexport default defineConfig({\n  testDir: \".\u002Fe2e\",\n  timeout: 30000,\n  expect: {\n    timeout: 5000,\n  },\n  fullyParallel: true,\n  forbidOnly: !!process.env.CI,\n  retries: process.env.CI ? 2 : 0,\n  workers: process.env.CI ? 1 : undefined,\n  reporter: [[\"html\"], [\"junit\", { outputFile: \"results.xml\" }]],\n  use: {\n    baseURL: \"http:\u002F\u002Flocalhost:3000\",\n    trace: \"on-first-retry\",\n    screenshot: \"only-on-failure\",\n    video: \"retain-on-failure\",\n  },\n  projects: [\n    { name: \"chromium\", use: { ...devices[\"Desktop Chrome\"] } },\n    { name: \"firefox\", use: { ...devices[\"Desktop Firefox\"] } },\n    { name: \"webkit\", use: { ...devices[\"Desktop Safari\"] } },\n    { name: \"mobile\", use: { ...devices[\"iPhone 13\"] } },\n  ],\n});\n```\n\n### Pattern 1: Page Object Model\n\n```typescript\n\u002F\u002F pages\u002FLoginPage.ts\nimport { Page, Locator } from \"@playwright\u002Ftest\";\n\nexport class LoginPage {\n  readonly page: Page;\n  readonly emailInput: Locator;\n  readonly passwordInput: Locator;\n  readonly loginButton: Locator;\n  readonly errorMessage: Locator;\n\n  constructor(page: Page) {\n    this.page = page;\n    this.emailInput = page.getByLabel(\"Email\");\n    this.passwordInput = page.getByLabel(\"Password\");\n    this.loginButton = page.getByRole(\"button\", { name: \"Login\" });\n    this.errorMessage = page.getByRole(\"alert\");\n  }\n\n  async goto() {\n    await this.page.goto(\"\u002Flogin\");\n  }\n\n  async login(email: string, password: string) {\n    await this.emailInput.fill(email);\n    await this.passwordInput.fill(password);\n    await this.loginButton.click();\n  }\n\n  async getErrorMessage(): Promise\u003Cstring> {\n    return (await this.errorMessage.textContent()) ?? \"\";\n  }\n}\n\n\u002F\u002F Test using Page Object\nimport { test, expect } from \"@playwright\u002Ftest\";\nimport { LoginPage } from \".\u002Fpages\u002FLoginPage\";\n\ntest(\"successful login\", async ({ page }) => {\n  const loginPage = new LoginPage(page);\n  await loginPage.goto();\n  await loginPage.login(\"user@example.com\", \"password123\");\n\n  await expect(page).toHaveURL(\"\u002Fdashboard\");\n  await expect(page.getByRole(\"heading\", { name: \"Dashboard\" })).toBeVisible();\n});\n\ntest(\"failed login shows error\", async ({ page }) => {\n  const loginPage = new LoginPage(page);\n  await loginPage.goto();\n  await loginPage.login(\"invalid@example.com\", \"wrong\");\n\n  const error = await loginPage.getErrorMessage();\n  expect(error).toContain(\"Invalid credentials\");\n});\n```\n\n### Pattern 2: Fixtures for Test Data\n\n```typescript\n\u002F\u002F fixtures\u002Ftest-data.ts\nimport { test as base } from \"@playwright\u002Ftest\";\n\ntype TestData = {\n  testUser: {\n    email: string;\n    password: string;\n    name: string;\n  };\n  adminUser: {\n    email: string;\n    password: string;\n  };\n};\n\nexport const test = base.extend\u003CTestData>({\n  testUser: async ({}, use) => {\n    const user = {\n      email: `test-${Date.now()}@example.com`,\n      password: \"Test123!@#\",\n      name: \"Test User\",\n    };\n    \u002F\u002F Setup: Create user in database\n    await createTestUser(user);\n    await use(user);\n    \u002F\u002F Teardown: Clean up user\n    await deleteTestUser(user.email);\n  },\n\n  adminUser: async ({}, use) => {\n    await use({\n      email: \"admin@example.com\",\n      password: process.env.ADMIN_PASSWORD!,\n    });\n  },\n});\n\n\u002F\u002F Usage in tests\nimport { test } from \".\u002Ffixtures\u002Ftest-data\";\n\ntest(\"user can update profile\", async ({ page, testUser }) => {\n  await page.goto(\"\u002Flogin\");\n  await page.getByLabel(\"Email\").fill(testUser.email);\n  await page.getByLabel(\"Password\").fill(testUser.password);\n  await page.getByRole(\"button\", { name: \"Login\" }).click();\n\n  await page.goto(\"\u002Fprofile\");\n  await page.getByLabel(\"Name\").fill(\"Updated Name\");\n  await page.getByRole(\"button\", { name: \"Save\" }).click();\n\n  await expect(page.getByText(\"Profile updated\")).toBeVisible();\n});\n```\n\n### Pattern 3: Waiting Strategies\n\n```typescript\n\u002F\u002F ❌ Bad: Fixed timeouts\nawait page.waitForTimeout(3000); \u002F\u002F Flaky!\n\n\u002F\u002F ✅ Good: Wait for specific conditions\nawait page.waitForLoadState(\"networkidle\");\nawait page.waitForURL(\"\u002Fdashboard\");\nawait page.waitForSelector('[data-testid=\"user-profile\"]');\n\n\u002F\u002F ✅ Better: Auto-waiting with assertions\nawait expect(page.getByText(\"Welcome\")).toBeVisible();\nawait expect(page.getByRole(\"button\", { name: \"Submit\" })).toBeEnabled();\n\n\u002F\u002F Wait for API response\nconst responsePromise = page.waitForResponse(\n  (response) =>\n    response.url().includes(\"\u002Fapi\u002Fusers\") && response.status() === 200,\n);\nawait page.getByRole(\"button\", { name: \"Load Users\" }).click();\nconst response = await responsePromise;\nconst data = await response.json();\nexpect(data.users).toHaveLength(10);\n\n\u002F\u002F Wait for multiple conditions\nawait Promise.all([\n  page.waitForURL(\"\u002Fsuccess\"),\n  page.waitForLoadState(\"networkidle\"),\n  expect(page.getByText(\"Payment successful\")).toBeVisible(),\n]);\n```\n\n### Pattern 4: Network Mocking and Interception\n\n```typescript\n\u002F\u002F Mock API responses\ntest(\"displays error when API fails\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fusers\", (route) => {\n    route.fulfill({\n      status: 500,\n      contentType: \"application\u002Fjson\",\n      body: JSON.stringify({ error: \"Internal Server Error\" }),\n    });\n  });\n\n  await page.goto(\"\u002Fusers\");\n  await expect(page.getByText(\"Failed to load users\")).toBeVisible();\n});\n\n\u002F\u002F Intercept and modify requests\ntest(\"can modify API request\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fusers\", async (route) => {\n    const request = route.request();\n    const postData = JSON.parse(request.postData() || \"{}\");\n\n    \u002F\u002F Modify request\n    postData.role = \"admin\";\n\n    await route.continue({\n      postData: JSON.stringify(postData),\n    });\n  });\n\n  \u002F\u002F Test continues...\n});\n\n\u002F\u002F Mock third-party services\ntest(\"payment flow with mocked Stripe\", async ({ page }) => {\n  await page.route(\"**\u002Fapi\u002Fstripe\u002F**\", (route) => {\n    route.fulfill({\n      status: 200,\n      body: JSON.stringify({\n        id: \"mock_payment_id\",\n        status: \"succeeded\",\n      }),\n    });\n  });\n\n  \u002F\u002F Test payment flow with mocked response\n});\n```\n\n## Cypress Patterns\n\n### Setup and Configuration\n\n```typescript\n\u002F\u002F cypress.config.ts\nimport { defineConfig } from \"cypress\";\n\nexport default defineConfig({\n  e2e: {\n    baseUrl: \"http:\u002F\u002Flocalhost:3000\",\n    viewportWidth: 1280,\n    viewportHeight: 720,\n    video: false,\n    screenshotOnRunFailure: true,\n    defaultCommandTimeout: 10000,\n    requestTimeout: 10000,\n    setupNodeEvents(on, config) {\n      \u002F\u002F Implement node event listeners\n    },\n  },\n});\n```\n\n### Pattern 1: Custom Commands\n\n```typescript\n\u002F\u002F cypress\u002Fsupport\u002Fcommands.ts\ndeclare global {\n  namespace Cypress {\n    interface Chainable {\n      login(email: string, password: string): Chainable\u003Cvoid>;\n      createUser(userData: UserData): Chainable\u003CUser>;\n      dataCy(value: string): Chainable\u003CJQuery\u003CHTMLElement>>;\n    }\n  }\n}\n\nCypress.Commands.add(\"login\", (email: string, password: string) => {\n  cy.visit(\"\u002Flogin\");\n  cy.get('[data-testid=\"email\"]').type(email);\n  cy.get('[data-testid=\"password\"]').type(password);\n  cy.get('[data-testid=\"login-button\"]').click();\n  cy.url().should(\"include\", \"\u002Fdashboard\");\n});\n\nCypress.Commands.add(\"createUser\", (userData: UserData) => {\n  return cy.request(\"POST\", \"\u002Fapi\u002Fusers\", userData).its(\"body\");\n});\n\nCypress.Commands.add(\"dataCy\", (value: string) => {\n  return cy.get(`[data-cy=\"${value}\"]`);\n});\n\n\u002F\u002F Usage\ncy.login(\"user@example.com\", \"password\");\ncy.dataCy(\"submit-button\").click();\n```\n\n### Pattern 2: Cypress Intercept\n\n```typescript\n\u002F\u002F Mock API calls\ncy.intercept(\"GET\", \"\u002Fapi\u002Fusers\", {\n  statusCode: 200,\n  body: [\n    { id: 1, name: \"John\" },\n    { id: 2, name: \"Jane\" },\n  ],\n}).as(\"getUsers\");\n\ncy.visit(\"\u002Fusers\");\ncy.wait(\"@getUsers\");\ncy.get('[data-testid=\"user-list\"]').children().should(\"have.length\", 2);\n\n\u002F\u002F Modify responses\ncy.intercept(\"GET\", \"\u002Fapi\u002Fusers\", (req) => {\n  req.reply((res) => {\n    \u002F\u002F Modify response\n    res.body.users = res.body.users.slice(0, 5);\n    res.send();\n  });\n});\n\n\u002F\u002F Simulate slow network\ncy.intercept(\"GET\", \"\u002Fapi\u002Fdata\", (req) => {\n  req.reply((res) => {\n    res.delay(3000); \u002F\u002F 3 second delay\n    res.send();\n  });\n});\n```\n\n## Advanced Patterns\n\n### Pattern 1: Visual Regression Testing\n\n```typescript\n\u002F\u002F With Playwright\nimport { test, expect } from \"@playwright\u002Ftest\";\n\ntest(\"homepage looks correct\", async ({ page }) => {\n  await page.goto(\"\u002F\");\n  await expect(page).toHaveScreenshot(\"homepage.png\", {\n    fullPage: true,\n    maxDiffPixels: 100,\n  });\n});\n\ntest(\"button in all states\", async ({ page }) => {\n  await page.goto(\"\u002Fcomponents\");\n\n  const button = page.getByRole(\"button\", { name: \"Submit\" });\n\n  \u002F\u002F Default state\n  await expect(button).toHaveScreenshot(\"button-default.png\");\n\n  \u002F\u002F Hover state\n  await button.hover();\n  await expect(button).toHaveScreenshot(\"button-hover.png\");\n\n  \u002F\u002F Disabled state\n  await button.evaluate((el) => el.setAttribute(\"disabled\", \"true\"));\n  await expect(button).toHaveScreenshot(\"button-disabled.png\");\n});\n```\n\n### Pattern 2: Parallel Testing with Sharding\n\n```typescript\n\u002F\u002F playwright.config.ts\nexport default defineConfig({\n  projects: [\n    {\n      name: \"shard-1\",\n      use: { ...devices[\"Desktop Chrome\"] },\n      grepInvert: \u002F@slow\u002F,\n      shard: { current: 1, total: 4 },\n    },\n    {\n      name: \"shard-2\",\n      use: { ...devices[\"Desktop Chrome\"] },\n      shard: { current: 2, total: 4 },\n    },\n    \u002F\u002F ... more shards\n  ],\n});\n\n\u002F\u002F Run in CI\n\u002F\u002F npx playwright test --shard=1\u002F4\n\u002F\u002F npx playwright test --shard=2\u002F4\n```\n\n### Pattern 3: Accessibility Testing\n\n```typescript\n\u002F\u002F Install: npm install @axe-core\u002Fplaywright\nimport { test, expect } from \"@playwright\u002Ftest\";\nimport AxeBuilder from \"@axe-core\u002Fplaywright\";\n\ntest(\"page should not have accessibility violations\", async ({ page }) => {\n  await page.goto(\"\u002F\");\n\n  const accessibilityScanResults = await new AxeBuilder({ page })\n    .exclude(\"#third-party-widget\")\n    .analyze();\n\n  expect(accessibilityScanResults.violations).toEqual([]);\n});\n\ntest(\"form is accessible\", async ({ page }) => {\n  await page.goto(\"\u002Fsignup\");\n\n  const results = await new AxeBuilder({ page }).include(\"form\").analyze();\n\n  expect(results.violations).toEqual([]);\n});\n```\n\n## Best Practices\n\n1. **Use Data Attributes**: `data-testid` or `data-cy` for stable selectors\n2. **Avoid Brittle Selectors**: Don't rely on CSS classes or DOM structure\n3. **Test User Behavior**: Click, type, see - not implementation details\n4. **Keep Tests Independent**: Each test should run in isolation\n5. **Clean Up Test Data**: Create and destroy test data in each test\n6. **Use Page Objects**: Encapsulate page logic\n7. **Meaningful Assertions**: Check actual user-visible behavior\n8. **Optimize for Speed**: Mock when possible, parallel execution\n\n```typescript\n\u002F\u002F ❌ Bad selectors\ncy.get(\".btn.btn-primary.submit-button\").click();\ncy.get(\"div > form > div:nth-child(2) > input\").type(\"text\");\n\n\u002F\u002F ✅ Good selectors\ncy.getByRole(\"button\", { name: \"Submit\" }).click();\ncy.getByLabel(\"Email address\").type(\"user@example.com\");\ncy.get('[data-testid=\"email-input\"]').type(\"user@example.com\");\n```\n\n## Common Pitfalls\n\n- **Flaky Tests**: Use proper waits, not fixed timeouts\n- **Slow Tests**: Mock external APIs, use parallel execution\n- **Over-Testing**: Don't test every edge case with E2E\n- **Coupled Tests**: Tests should not depend on each other\n- **Poor Selectors**: Avoid CSS classes and nth-child\n- **No Cleanup**: Clean up test data after each test\n- **Testing Implementation**: Test user behavior, not internals\n\n## Debugging Failing Tests\n\n```typescript\n\u002F\u002F Playwright debugging\n\u002F\u002F 1. Run in headed mode\nnpx playwright test --headed\n\n\u002F\u002F 2. Run in debug mode\nnpx playwright test --debug\n\n\u002F\u002F 3. Use trace viewer\nawait page.screenshot({ path: 'screenshot.png' });\nawait page.video()?.saveAs('video.webm');\n\n\u002F\u002F 4. Add test.step for better reporting\ntest('checkout flow', async ({ page }) => {\n    await test.step('Add item to cart', async () => {\n        await page.goto('\u002Fproducts');\n        await page.getByRole('button', { name: 'Add to Cart' }).click();\n    });\n\n    await test.step('Proceed to checkout', async () => {\n        await page.goto('\u002Fcart');\n        await page.getByRole('button', { name: 'Checkout' }).click();\n    });\n});\n\n\u002F\u002F 5. Inspect page state\nawait page.pause();  \u002F\u002F Pauses execution, opens inspector\n```\n",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Fe2e-testing-patterns",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill e2e-testing-patterns",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill e2e-testing-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill e2e-testing-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fdeveloper-essentials\u002Fskills\u002Fe2e-testing-patterns\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]