Back to catalog

playwright-visual-testing

Browser automation, visual testing, and screenshot validation using Playwright MCP server for accelerated web development. Master visual regression testing, automated UI testing, and cross-browser validation.

  • Category: discovered
  • Tags: github, community
  • Version: 1.0.0
  • Author: walid
  • Downloads: 0
  • Updated: 2025-11-22

Download the latest version (v1.0.0) from this page.

SKILL.md

---
name: playwright-visual-testing
description: Browser automation, visual testing, and screenshot validation using Playwright MCP server for accelerated web development. Master visual regression testing, automated UI testing, and cross-browser validation.
---

# Playwright Visual Testing & Browser Automation

A comprehensive skill for browser automation and visual testing using Playwright MCP server integration. This skill enables rapid UI testing, visual regression detection, automated browser interactions, and cross-browser validation for modern web applications.

## When to Use This Skill

Use this skill when:

- Testing web applications across multiple browsers (Chromium, Firefox, WebKit)
- Implementing visual regression testing for UI changes
- Automating user interactions for QA and testing
- Validating responsive designs across different viewports
- Taking screenshots for documentation or bug reports
- Testing form submissions and user workflows
- Verifying accessibility of web interfaces
- Debugging browser-specific issues
- Creating automated E2E test suites
- Validating web applications before deployment
- Testing PWAs and single-page applications
- Capturing visual states for design reviews

## Core Concepts

### Playwright Browser Automation Philosophy

Playwright provides reliable end-to-end testing for modern web apps:

- **Auto-wait**: Automatically waits for elements to be actionable before interacting
- **Web-first assertions**: Retry assertions until they pass or timeout
- **Cross-browser**: Test on Chromium, Firefox, and WebKit with single API
- **Accessibility snapshots**: Navigate pages using semantic structure, not visual rendering
- **Visual testing**: Compare screenshots to detect visual regressions
- **Network control**: Intercept and mock network requests
- **Multi-context**: Test multiple scenarios in isolated browser contexts

### Key Playwright Entities

1. **Browser**: The browser instance (Chromium, Firefox, WebKit)
2. **Page**: A single page/tab in the browser
3. **Locator**: Element selector using accessibility tree
4. **Snapshot**: Accessibility tree representation of page state
5. **Screenshot**: Visual capture of page or element
6. **Network Request**: HTTP requests made by the page
7. **Console Messages**: Browser console output
8. **Dialog**: Browser prompts, alerts, confirms

### Visual Testing Workflow

1. **Navigate** to the target page
2. **Wait** for page to stabilize (animations, loading)
3. **Capture** accessibility snapshot for context
4. **Take screenshot** of page or specific elements
5. **Compare** against baseline (optional)
6. **Validate** visual appearance and functionality
7. **Document** results and issues

## Playwright MCP Server Tools Reference

### Browser Lifecycle Management

#### browser_navigate
Navigate to a URL in the current page.

**Parameters:**
```
url: The URL to navigate to (required)
```

**Example:**
```javascript
url: "https://example.com"
```

**Best Practices:**
- Use full URLs including protocol (https://)
- Wait for navigation to complete before taking actions
- Handle redirects and page transitions

#### browser_navigate_back
Navigate back to the previous page in history.

**Parameters:** None

**Example:**
```javascript
// Navigate back after clicking a link
```

**Use Cases:**
- Testing navigation flows
- Verifying back button behavior
- Multi-step form navigation

#### browser_close
Close the current browser page.

**Parameters:** None

**When to Use:**
- Clean up after testing
- Free system resources
- Reset browser state

#### browser_resize
Resize the browser viewport.

**Parameters:**
```
width: Width in pixels (required)
height: Height in pixels (required)
```

**Common Viewports:**
```javascript
// Mobile
width: 375, height: 667  // iPhone SE
width: 414, height: 896  // iPhone XR

// Tablet
width: 768, height: 1024  // iPad

// Desktop
width: 1280, height: 720  // HD
width: 1920, height: 1080 // Full HD
```

**Example:**
```javascript
width: 375
height: 667
```

### Page Inspection & Snapshots

#### browser_snapshot
Capture accessibility snapshot of the current page.

**Parameters:** None

**Returns:**
- Accessibility tree with semantic structure
- Element references (ref) for interactions
- Text content and roles
- Interactive elements and states

**Why Use Snapshots:**
- Better than screenshots for automation
- Semantic understanding of page structure
- Element references for precise interactions
- Faster than visual parsing
- Works without visual rendering

**Example Snapshot Structure:**
```
heading "Welcome" [ref=123]
  text "to our site"
button "Sign In" [ref=456]
textbox "Email" [ref=789]
  value: ""
```

#### browser_take_screenshot
Take a screenshot of the current page or element.

**Parameters:**
```
filename: Output filename (optional, defaults to page-{timestamp}.png)
type: Image format - "png" or "jpeg" (default: png)
fullPage: Capture full scrollable page (default: false)
element: Human-readable element description (optional)
ref: Element reference from snapshot (optional, requires element)
```

**Screenshot Types:**

1. **Viewport Screenshot** (default):
```javascript
filename: "homepage-viewport.png"
```

2. **Full Page Screenshot**:
```javascript
filename: "homepage-full.png"
fullPage: true
```

3. **Element Screenshot**:
```javascript
filename: "header.png"
element: "main header navigation"
ref: "123"
```

**Best Practices:**
- Use descriptive filenames with context
- PNG for UI elements (lossless)
- JPEG for photos/images (smaller size)
- Full page for documentation
- Element screenshots for focused testing

### Browser Interaction

#### browser_click
Perform click on an element.

**Parameters:**
```
element: Human-readable element description (required)
ref: Element reference from snapshot (required)
button: "left", "right", or "middle" (default: left)
doubleClick: true for double-click (default: false)
modifiers: Array of modifier keys ["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]
```

**Examples:**

1. **Basic Click**:
```javascript
element: "Submit button"
ref: "456"
```

2. **Right Click**:
```javascript
element: "Context menu trigger"
ref: "789"
button: "right"
```

3. **Click with Modifier**:
```javascript
element: "Link to open in new tab"
ref: "123"
modifiers: ["ControlOrMeta"]
```

4. **Double Click**:
```javascript
element: "Word to select"
ref: "321"
doubleClick: true
```

#### browser_type
Type text into an editable element.

**Parameters:**
```
element: Human-readable element description (required)
ref: Element reference from snapshot (required)
text: Text to type (required)
slowly: Type one character at a time (default: false)
submit: Press Enter after typing (default: false)
```

**Examples:**

1. **Form Input**:
```javascript
element: "Email textbox"
ref: "123"
text: "user@example.com"
```

2. **Search with Submit**:
```javascript
element: "Search field"
ref: "456"
text: "playwright testing"
submit: true
```

3. **Character-by-Character** (triggers key handlers):
```javascript
element: "Auto-complete input"
ref: "789"
text: "New York"
slowly: true
```

#### browser_press_key
Press a keyboard key.

**Parameters:**
```
key: Key name or character (required)
```

**Common Keys:**
```
ArrowLeft, ArrowRight, ArrowUp, ArrowDown
Enter, Escape, Tab, Backspace, Delete
Home, End, PageUp, PageDown
F1-F12
Control, Alt, Shift, Meta
```

**Examples:**
```javascript
// Navigation
key: "ArrowDown"

// Submit form
key: "Enter"

// Close dialog
key: "Escape"

// Tab through fields
key: "Tab"
```

#### browser_fill_form
Fill multiple form fields at once.

**Parameters:**
```
fields: Array of field objects (required)
  - name: Human-readable field name
  - type: "textbox", "checkbox", "radio", "combobox", "slider"
  - ref: Element reference from snapshot
  - value: Value to set (string, "true"/"false" for checkboxes)
```

**Example:**
```javascript
fields: [
  {
    name: "Username",
    type: "textbox",
    ref: "123",
    value: "john_doe"
  },
  {
    name: "Password",
    type: "textbox",
    ref: "456",
    value: "secretpass123"
  },
  {
    name: "Remember me",
    type: "checkbox",
    ref: "789",
    value: "true"
  }
]
```

#### browser_select_option
Select option from dropdown.

**Parameters:**
```
element: Human-readable element description (required)
ref: Element reference from snapshot (required)
values: Array of values to select (required)
```

**Example:**
```javascript
element: "Country dropdown"
ref: "123"
values: ["United States"]
```

**Multi-select:**
```javascript
element: "Programming languages"
ref: "456"
values: ["JavaScript", "Python", "Go"]
```

#### browser_hover
Hover over an element.

**Parameters:**
```
element: Human-readable element description (required)
ref: Element reference from snapshot (required)
```

**Use Cases:**
- Trigger tooltips
- Show dropdown menus
- Test hover states
- Reveal hidden elements

**Example:**
```javascript
element: "Help icon"
ref: "123"
```

#### browser_drag
Drag and drop between elements.

**Parameters:**
```
startElement: Source element description (required)
startRef: Source element reference (required)
endElement: Target element description (required)
endRef: Target element reference (required)
```

**Example:**
```javascript
startElement: "Task card"
startRef: "123"
endElement: "Done column"
endRef: "456"
```

**Use Cases:**
- Drag-and-drop interfaces
- Reordering lists
- File uploads
- Kanban boards

### Advanced Interactions

#### browser_evaluate
Execute JavaScript in page context.

**Parameters:**
```
function: JavaScript function as string (required)
element: Element description (optional)
ref: Element reference (optional, requires element)
```

**Examples:**

1. **Page-level Script**:
```javascript
function: "() => { return document.title; }"
```

2. **Element-level Script**:
```javascript
element: "Custom widget"
ref: "123"
function: "(element) => { return element.getAttribute('data-value'); }"
```

**Common Use Cases:**
```javascript
// Get page title
function: "() => document.title"

// Scroll to bottom
function: "() => window.scrollTo(0, document.body.scrollHeight)"

// Get element dimensions
function: "(element) => { const rect = element.getBoundingClientRect(); return { width: rect.width, height: rect.height }; }"

// Set local storage
function: "() => localStorage.setItem('theme', 'dark')"

// Get computed style
function: "(element) => getComputedStyle(element).backgroundColor"
```

#### browser_file_upload
Upload files to file input.

**Parameters:**
```
paths: Array of absolute file paths (required)
  - Omit or pass empty array to cancel file chooser
```

**Example:**
```javascript
paths: [
  "/Users/user/Documents/resume.pdf",
  "/Users/user/Photos/headshot.jpg"
]
```

**Single File:**
```javascript
paths: ["/Users/user/Downloads/report.csv"]
```

**Cancel Upload:**
```javascript
paths: []
```

### Browser State & Debugging

#### browser_console_messages
Get console messages from the browser.

**Parameters:**
```
onlyErrors: Return only error messages (default: false)
```

**Returns:**
- All console.log, console.error, console.warn messages
- Timestamps and message types
- JavaScript errors and stack traces

**Examples:**

1. **All Messages**:
```javascript
onlyErrors: false
```

2. **Errors Only**:
```javascript
onlyErrors: true
```

**Use Cases:**
- Debug JavaScript errors
- Monitor API failures
- Track console warnings
- Verify logging behavior

#### browser_network_requests
Get all network requests since page load.

**Parameters:** None

**Returns:**
- URL, method, status code
- Request/response headers
- Timing information
- Request/response bodies

**Use Cases:**
- Verify API calls
- Check resource loading
- Debug failed requests
- Monitor performance
- Validate analytics tracking

#### browser_handle_dialog
Respond to browser dialogs.

**Parameters:**
```
accept: Accept or dismiss dialog (required)
promptText: Text for prompt dialogs (optional)
```

**Dialog Types:**
- alert: Information message
- confirm: Yes/No choice
- prompt: Text input request
- beforeunload: Page navigation warning

**Examples:**

1. **Accept Alert**:
```javascript
accept: true
```

2. **Dismiss Confirm**:
```javascript
accept: false
```

3. **Answer Prompt**:
```javascript
accept: true
promptText: "John Doe"
```

#### browser_wait_for
Wait for conditions before proceeding.

**Parameters:**
```
text: Wait for text to appear (optional)
textGone: Wait for text to disappear (optional)
time: Wait for specified seconds (optional)
```

**Examples:**

1. **Wait for Text**:
```javascript
text: "Loading complete"
```

2. **Wait for Removal**:
```javascript
textGone: "Loading..."
```

3. **Fixed Wait**:
```javascript
time: 2
```

**Best Practices:**
- Prefer waiting for specific conditions over fixed time
- Use for dynamic content loading
- Wait for animations to complete
- Ensure page stability before screenshots

### Tab Management

#### browser_tabs
Manage browser tabs.

**Parameters:**
```
action: "list", "new", "close", "select" (required)
index: Tab index for close/select (optional)
```

**Actions:**

1. **List Tabs**:
```javascript
action: "list"
```

2. **New Tab**:
```javascript
action: "new"
```

3. **Close Tab**:
```javascript
action: "close"
index: 1  // Optional, closes current if omitted
```

4. **Switch Tab**:
```javascript
action: "select"
index: 0
```

**Use Cases:**
- Multi-tab workflows
- Testing tab-specific features
- Opening links in new tabs
- Managing multiple sessions

### Browser Installation

#### browser_install
Install the browser specified in config.

**Parameters:** None

**When to Use:**
- First-time setup
- "Browser not installed" errors
- Updating browser version
- CI/CD environment setup

## Visual Testing Workflow Patterns

### Pattern 1: Basic Visual Regression Test

**Scenario:** Verify homepage hasn't changed visually

```workflow
1. Navigate to page
   - Use browser_navigate with target URL
   - Wait for page to load completely

2. Capture baseline
   - Take full-page screenshot
   - Use browser_snapshot for context
   - Document visible elements

3. Make changes (if testing changes)
   - Update code, deploy
   - Clear cache

4. Capture new state
   - Navigate to same URL
   - Take identical screenshot
   - Compare manually or with tools

5. Validate differences
   - Expected changes present
   - No unexpected regressions
   - Document findings
```

### Pattern 2: Responsive Design Testing

**Scenario:** Test layout across devices

```workflow
1. Define viewports
   - Mobile: 375x667 (iPhone SE)
   - Tablet: 768x1024 (iPad)
   - Desktop: 1920x1080 (Full HD)

2. For each viewport:
   a. Resize browser
      - browser_resize with dimensions

   b. Navigate to page
      - browser_navigate to URL

   c. Wait for layout
      - browser_wait_for with condition

   d. Capture snapshot
      - browser_snapshot for structure

   e. Take screenshot
      - browser_take_screenshot with descriptive name
      - Include viewport in filename

3. Compare layouts
   - Verify responsive breakpoints
   - Check element reflow
   - Validate mobile navigation
   - Ensure content accessibility

4. Document issues
   - Screenshot any problems
   - Note viewport where issue occurs
   - Record expected vs actual behavior
```

### Pattern 3: Form Testing Workflow

**Scenario:** Test multi-step form submission

```workflow
1. Navigate to form
   - browser_navigate to form URL
   - browser_snapshot to get field refs

2. Fill form fields
   - Use browser_fill_form for batch entry
   - Or individual browser_type for each field
   - Include validation triggers

3. Test validation
   - Submit with invalid data
   - browser_snapshot to see errors
   - Screenshot error states
   - Verify error messages appear

4. Complete valid submission
   - Fill all required fields
   - browser_click submit button
   - Wait for success message
   - browser_wait_for confirmation text

5. Verify results
   - Check success page
   - Verify data submission
   - Screenshot confirmation
   - Check network requests
```

### Pattern 4: Element-Specific Visual Testing

**Scenario:** Test individual component changes

```workflow
1. Navigate to component page
   - browser_navigate to page
   - browser_snapshot for structure

2. Locate component
   - Find element ref from snapshot
   - Verify component is visible

3. Test states
   a. Default state
      - Take element screenshot
      - Document initial appearance

   b. Hover state
      - browser_hover on element
      - Take element screenshot
      - Compare with default

   c. Active/focused state
      - browser_click on element
      - Take element screenshot
      - Verify visual feedback

   d. Error state (if applicable)
      - Trigger validation error
      - Take element screenshot
      - Verify error styling

4. Document state changes
   - Compare screenshots
   - Note expected behaviors
   - Report any issues
```

### Pattern 5: Cross-Browser Testing

**Scenario:** Verify consistency across browsers

```workflow
1. Define browser matrix
   - Chromium (Chrome/Edge)
   - Firefox
   - WebKit (Safari)

2. For each browser:
   a. Configure browser
      - Set in MCP server config

   b. Run test suite
      - Navigate to pages
      - Capture snapshots
      - Take screenshots
      - Test interactions

   c. Document results
      - Save browser-specific screenshots
      - Note rendering differences
      - Log browser-specific bugs

3. Compare results
   - Side-by-side screenshots
   - Functionality differences
   - Performance variations
   - CSS rendering issues

4. Address discrepancies
   - Fix critical cross-browser bugs
   - Document acceptable differences
   - Add browser-specific styles if needed
```

### Pattern 6: E2E User Journey Testing

**Scenario:** Complete user workflow validation

```workflow
1. Start journey
   - browser_navigate to landing page
   - browser_snapshot initial state
   - Screenshot starting point

2. Authentication
   - Navigate to login
   - Fill credentials with browser_fill_form
   - Submit form
   - Wait for redirect
   - Screenshot logged-in state

3. Main workflow steps
   For each step:
   - Take snapshot before action
   - Perform user action
   - Wait for completion
   - Take screenshot after action
   - Verify expected state

4. Complete transaction
   - Submit final action
   - Wait for confirmation
   - Screenshot success state
   - Verify completion message

5. Cleanup
   - Logout if needed
   - Screenshot final state
   - Document journey results
```

### Pattern 7: Accessibility Snapshot Testing

**Scenario:** Verify semantic structure and accessibility

```workflow
1. Navigate to page
   - browser_navigate to URL

2. Capture accessibility snapshot
   - browser_snapshot for semantic tree
   - Review element roles
   - Check heading hierarchy
   - Verify labels and descriptions

3. Validate structure
   - Proper heading levels (h1 → h2 → h3)
   - Form inputs have labels
   - Buttons have accessible names
   - Interactive elements have roles
   - ARIA attributes present

4. Test keyboard navigation
   - browser_press_key "Tab"
   - Snapshot after each tab
   - Verify focus indicators
   - Ensure logical tab order
   - Test skip links

5. Test screen reader experience
   - Review snapshot text content
   - Verify alt text present
   - Check ARIA live regions
   - Validate semantic landmarks
   - Ensure meaningful structure

6. Document findings
   - Screenshot accessibility tree
   - Note missing labels
   - Report hierarchy issues
   - Suggest improvements
```

## Browser Automation Best Practices

### Screenshot Best Practices

1. **Consistent Naming Convention**
```
{page}-{viewport}-{state}-{timestamp}.png

Examples:
homepage-desktop-default-1634567890.png
login-mobile-error-1634567891.png
checkout-tablet-success-1634567892.png
```

2. **Filename Organization**
```
screenshots/
  ├── baselines/
  │   ├── homepage-desktop.png
  │   ├── homepage-mobile.png