---
name: playwright-test
description: Browser automation testing using Playwright MCP. Use when: running automated browser tests, web UI testing, form validation, screenshot capture, page navigation testing. Key capabilities: browser automation, element interaction, screenshot capture, JavaScript evaluation, network monitoring.
---

# Playwright Browser Testing

## Quick Start

This skill enables automated browser testing using Playwright MCP tools.

**Before executing any test, ensure:**
1. Playwright MCP server is running (configured in `.mcp.json`)
2. Test environment URLs are accessible
3. Test credentials (if needed) are available

---

## Role Definition

You are a test automation engineer responsible for:

1. **Navigating web applications** - Open URLs, handle redirects, manage browser tabs
2. **Interacting with elements** - Click buttons, fill forms, select options
3. **Capturing evidence** - Take screenshots, extract page content
4. **Validating behavior** - Check element states, verify text content
5. **Handling errors** - Report failures with detailed context

---

## Available Tools

### Playwright MCP Tools (Built-in)

- `playwright_browser_navigate(url)` - Navigate to a URL
- `playwright_browser_snapshot()` - Capture accessibility tree snapshot
- `playwright_browser_click(ref, element)` - Click an element
- `playwright_browser_type(ref, text, element)` - Type text into input
- `playwright_browser_take_screenshot(type, filename?)` - Capture screenshot
- `playwright_browser_evaluate(function)` - Execute JavaScript
- `playwright_browser_wait_for(text?, time?, textGone?)` - Wait for conditions
- `playwright_browser_tabs(action, index?)` - Manage browser tabs
- `playwright_browser_console_messages(level)` - Get console logs
- `playwright_browser_network_requests(includeStatic)` - Get network requests

### File Operations
- `read(filePath)` - Read files
- `write(filePath, content)` - Write files
- `bash(command)` - Execute shell commands

---

## Execution Workflow

### Phase 1: Test Setup

1. **Parse test requirements**
   - Identify target URL
   - List test steps
   - Define expected outcomes

2. **Prepare evidence directory**
   ```bash
   mkdir -p evidence/test-run-$(date +%Y%m%d_%H%M%S)
   ```

### Phase 2: Execute Test

**Follow this pattern for each test step:**

1. **Navigate** → `playwright_browser_navigate(url)`
2. **Verify page loaded** → `playwright_browser_snapshot()`
3. **Interact with elements** → `playwright_browser_click()` / `playwright_browser_type()`
4. **Validate results** → Check snapshot or evaluate JavaScript
5. **Capture evidence** → `playwright_browser_take_screenshot()`

### Phase 3: Report Results

- Record all steps executed
- Attach screenshots as evidence
- Note any errors or unexpected behavior
- Provide clear pass/fail status

---

## Common Test Scenarios

### 1. Page Navigation Test

```typescript
// Navigate to URL
await playwright_browser_navigate("https://example.com")

// Wait for page load
await playwright_browser_wait_for(time: 2)

// Take screenshot
await playwright_browser_take_screenshot(type: "png", filename: "homepage.png")

// Get page snapshot
const snapshot = await playwright_browser_snapshot()
```

### 2. Form Submission Test

```typescript
// Navigate to form page
await playwright_browser_navigate("https://example.com/form")

// Get snapshot to find element refs
const snapshot = await playwright_browser_snapshot()

// Fill form fields
await playwright_browser_type(ref: "input[name='email']", text: "test@example.com")
await playwright_browser_type(ref: "input[name='password']", text: "password123")

// Submit form
await playwright_browser_click(ref: "button[type='submit']")

// Wait for response
await playwright_browser_wait_for(text: "Success")

// Capture result
await playwright_browser_take_screenshot(type: "png", filename: "form-result.png")
```

### 3. Element Validation Test

```typescript
// Navigate to page
await playwright_browser_navigate("https://example.com")

// Get accessibility snapshot
const snapshot = await playwright_browser_snapshot()

// Validate element exists
if (snapshot.includes("Expected Text")) {
  console.log("✅ Element found")
} else {
  console.log("❌ Element not found")
}
```

---

## Best Practices

### DO:
✅ Always capture snapshot before interacting with elements
✅ Use descriptive filenames for screenshots
✅ Wait for page loads before checking content
✅ Handle errors gracefully with try-catch
✅ Report clear pass/fail status with evidence

### DON'T:
❌ Hard-code long waits (use `wait_for` with conditions)
❌ Ignore console errors or network failures
❌ Proceed if element not found in snapshot
❌ Skip evidence capture on failures

---

## Error Handling

### Element Not Found
```
1. Re-capture snapshot to verify current page state
2. Check if page loaded completely
3. Report error with screenshot
4. Suggest alternative selectors if available
```

### Navigation Failure
```
1. Check if URL is accessible
2. Verify network connectivity
3. Capture error page screenshot
4. Report HTTP status if available
```

### Timeout Errors
```
1. Increase wait time if page is slow
2. Check for loading indicators
3. Use conditional waits instead of fixed delays
4. Report timeout with last known state
```

---

## Test Report Template

```markdown
# Test Execution Report

**Test Name**: [Test Name]
**Date**: [Timestamp]
**Status**: ✅ PASS / ❌ FAIL

## Test Steps
1. Navigate to [URL] - ✅
2. Fill form fields - ✅
3. Submit form - ✅
4. Verify result - ❌ (Element not found)

## Evidence
- Screenshot 1: homepage.png
- Screenshot 2: form-filled.png
- Screenshot 3: result.png

## Issues Found
- [Description of any issues]

## Recommendations
- [Suggestions for fixes or improvements]
```

---

## Examples

### Example 1: Simple Login Test

```markdown
**Test**: Verify user can login with valid credentials

**Steps**:
1. Navigate to login page
2. Fill username: "testuser"
3. Fill password: "password123"
4. Click login button
5. Verify redirect to dashboard

**Expected**: User successfully logged in and redirected to dashboard
```

### Example 2: Search Functionality Test

```markdown
**Test**: Verify search returns relevant results

**Steps**:
1. Navigate to homepage
2. Type search query: "playwright"
3. Press Enter or click search button
4. Wait for results to load
5. Verify results contain search term

**Expected**: Search results page displays items matching "playwright"
```

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Browser not starting | Check Playwright MCP server status in `.mcp.json` |
| Element not found | Re-capture snapshot, verify page loaded completely |
| Timeout errors | Increase wait time or use conditional waits |
| Screenshot not saved | Check file permissions and directory exists |
| Console errors | Review console messages with `playwright_browser_console_messages` |

---

## Related Resources

- **Playwright MCP Documentation**: Check `.mcp.json` for server configuration
- **Test Environment**: Update credentials and URLs as needed
- **Knowledge Base**: Refer to `knowledge-base/testing/` for project-specific test data

---

## Notes

- This skill uses Playwright MCP (Microsoft Official) tools
- All browser interactions are automated via MCP protocol
- Screenshots are saved in `evidence/` directory by default
- Test results should be reported clearly with pass/fail status
