AgentSkillsCN

webapp-playwright-testing

利用 Playwright MCP 进行浏览器自动化测试,打造 Web 应用测试工具集。适用于需要浏览页面、点击元素、填写表单、截取屏幕截图、验证 UI 组件、检查控制台日志、调试前端问题,或验证响应式设计的场景。支持实时浏览器交互与无障碍快照功能。

SKILL.md
--- frontmatter
name: webapp-playwright-testing
description: Browser automation toolkit using Playwright MCP for testing web applications. Use when asked to navigate pages, click elements, fill forms, take screenshots, verify UI components, check console logs, debug frontend issues, or validate responsive design. Supports live browser interaction and accessibility snapshots.

Web Application Testing

This skill enables comprehensive browser-based testing and debugging for web applications using Playwright MCP. It provides live browser interaction, UI validation, screenshot capture, console log inspection, and accessibility verification to ensure your web application behaves as expected.

Activation: This skill is triggered when you need to interact with a browser, validate UI elements, capture screenshots, or debug web application issues.

When to Use This Skill

Use this skill when you need to:

  • Create Playwright tests for web applications
  • Test frontend functionality in a real browser
  • Verify UI behavior and interactions
  • Debug web application issues
  • Capture screenshots for documentation or debugging
  • Inspect browser console logs
  • Validate form submissions and user flows
  • Check responsive design across viewports

Prerequisites

  • Node.js installed on the system (v18+)
  • A locally running web application (or accessible URL)
  • Playwright MCP server configured
  • Playwright will be installed automatically if not present

Playwright MCP Tools Reference

Navigation & Interaction

ToolPurposeExample Query
browser_navigateGo to a URL"Navigate to http://localhost:3000/login"
browser_clickClick elements"Click the Submit button"
browser_fill_formFill input fields"Fill the email field with test@example.com"
browser_hoverHover over elements"Hover over the dropdown menu"
browser_press_keyKeyboard input"Press Enter"
browser_select_optionSelect from dropdown"Select 'Option 1' from the dropdown"

Validation & Capture

ToolPurposeExample Query
browser_snapshotGet accessibility tree"Get the accessibility snapshot"
browser_take_screenshotCapture visual state"Take a screenshot"
browser_console_messagesView browser logs"Check for console errors"
browser_network_requestsMonitor API calls"Show network requests"

Browser Management

ToolPurposeExample Query
browser_resizeChange viewport"Resize to mobile (375x667)"
browser_tabsManage browser tabs"List open tabs"
browser_closeClose browser"Close the browser"

Core Capabilities

1. Browser Automation

  • Navigate to URLs
  • Click buttons and links
  • Fill form fields
  • Select dropdowns
  • Handle dialogs and alerts

2. Verification

  • Assert element presence
  • Verify text content
  • Check element visibility
  • Validate URLs
  • Test responsive behavior

3. Debugging

  • Capture screenshots
  • View console logs
  • Inspect network requests
  • Debug failed tests

Usage Examples

Example 1: Basic Navigation Test

typescript
// Navigate to a page and verify heading
await page.goto('http://localhost:3000');
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();

Example 2: Form Interaction (Role-Based Locators)

typescript
// Fill out and submit a form using accessible locators
await page.getByRole('textbox', { name: 'Username' }).fill('testuser');
await page.getByRole('textbox', { name: 'Password' }).fill('password123');
await page.getByRole('button', { name: 'Login' }).click();
await expect(page).toHaveURL(/.*dashboard/);

Example 3: Screenshot Capture

typescript
// Capture a full-page screenshot for debugging
await page.screenshot({ path: 'debug.png', fullPage: true });

Example 4: Accessibility Snapshot Assertion

typescript
// Verify page structure with aria snapshot
await expect(page.getByRole('main')).toMatchAriaSnapshot(`
  - main:
    - heading "Welcome" [level=1]
    - form:
      - textbox "Email"
      - textbox "Password"
      - button "Login"
`);

Guidelines

  1. Always verify the app is running - Check that the local server is accessible before running tests
  2. Use explicit waits - Wait for elements or navigation to complete before interacting
  3. Capture screenshots on failure - Take screenshots to help debug issues
  4. Clean up resources - Always close the browser when done
  5. Handle timeouts gracefully - Set reasonable timeouts for slow operations
  6. Test incrementally - Start with simple interactions before complex flows
  7. Use selectors wisely - Prefer data-testid or role-based selectors over CSS classes

Common Patterns

Pattern: Wait for Element (Role-Based)

typescript
await page.getByRole('button', { name: 'Submit' }).waitFor({ state: 'visible' });

Pattern: Check if Element Exists

typescript
const exists = await page.getByRole('alert').count() > 0;

Pattern: Capture Console Logs

typescript
page.on('console', msg => console.log(`[${msg.type()}] ${msg.text()}`));

Pattern: Handle Errors with Screenshot

typescript
try {
  await page.getByRole('button', { name: 'Submit' }).click();
} catch (error) {
  await page.screenshot({ path: 'error.png' });
  throw error;
}

Pattern: Test Responsive Viewports

typescript
const viewports = [
  { width: 375, height: 667, name: 'mobile' },
  { width: 768, height: 1024, name: 'tablet' },
  { width: 1920, height: 1080, name: 'desktop' },
];

for (const vp of viewports) {
  await page.setViewportSize({ width: vp.width, height: vp.height });
  await page.screenshot({ path: `${vp.name}.png` });
}

Step-by-Step Workflows

Workflow 1: Validate a Page with Playwright MCP

  1. Navigate to the page

    code
    "Navigate to http://localhost:3000/login"
    
  2. Get accessibility snapshot

    code
    "Get the accessibility snapshot"
    
  3. Verify expected elements exist

    • Check for form fields, buttons, headings in the snapshot
  4. Take a screenshot for documentation

    code
    "Take a screenshot"
    
  5. Check for console errors

    code
    "Show console messages"
    

Workflow 2: Debug a Failing Test

  1. Navigate to the problematic page

    code
    "Navigate to http://localhost:3000/checkout"
    
  2. Capture initial state

    code
    "Take a screenshot"
    
  3. Get accessibility snapshot to understand structure

    code
    "Get the accessibility snapshot"
    
  4. Identify the correct locator from the snapshot

  5. Test the interaction

    code
    "Click the 'Add to Cart' button"
    
  6. Verify result and capture evidence

    code
    "Take a screenshot"
    "Check for console errors"
    

Workflow 3: Test Responsive Design

  1. Navigate to the page

    code
    "Navigate to http://localhost:3000"
    
  2. Test mobile viewport

    code
    "Resize browser to 375x667"
    "Take a screenshot"
    "Verify hamburger menu is visible"
    
  3. Test tablet viewport

    code
    "Resize browser to 768x1024"
    "Take a screenshot"
    
  4. Test desktop viewport

    code
    "Resize browser to 1920x1080"
    "Verify navigation links are visible"
    

Troubleshooting

ProblemCauseSolution
Element not foundWrong locator or element not renderedUse browser_snapshot to verify structure
Timeout waiting for elementElement hidden or slow to loadCheck for overlays, increase timeout
Strict mode violationMultiple elements match locatorAdd more specific filters like { exact: true }
Click interceptedAnother element covering targetScroll into view or wait for overlay to close
Console errors in appJavaScript runtime errorsUse browser_console_messages to debug
Screenshot blankPage not fully loadedWait for network idle or specific element
Form submission failsValidation errors not visibleCheck for error messages in snapshot

Locator Strategy (Priority Order)

typescript
// ✅ BEST: Role-based (accessible, resilient)
page.getByRole('button', { name: 'Submit' })
page.getByRole('textbox', { name: 'Email' })
page.getByRole('link', { name: 'Sign up' })

// ✅ GOOD: User-facing text
page.getByLabel('Email address')
page.getByPlaceholder('Enter your email')
page.getByText('Welcome back')

// ✅ GOOD: Test IDs (stable, explicit)
page.getByTestId('submit-button')

// ⚠️ AVOID: CSS selectors (brittle)
page.locator('.btn-primary')

// ❌ NEVER: XPath (extremely brittle)
page.locator('//div[@class="container"]/button[1]')

Limitations

  • Requires Node.js environment (v18+)
  • Cannot test native mobile apps (use Appium or Detox instead)
  • Complex authentication flows may require session storage or API login
  • Some modern frameworks with shadow DOM require specific configuration
  • Heavy animations may require disabling for stable tests

References


Quick Commands

TaskPlaywright MCP Query
Open page"Navigate to {URL}"
Check structure"Get the accessibility snapshot"
Capture evidence"Take a screenshot"
Fill form"Fill the {field} with {value}"
Click element"Click the {name} button"
Check errors"Show console messages"
Test mobile"Resize browser to 375x667"