Playwright MCP for Browser Automation
What is Playwright MCP?โ
Playwright MCP combines the power of Playwright browser automation with AI intelligence. It enables LLMs to directly interact with web pages, automatically generating end-to-end test cases through real browser interactions.
Key Capabilitiesโ
- ๐ค AI-Driven Browser Control - Let AI navigate your application
- ๐ Automatic Test Generation - Create tests from real interactions
- ๐ Site Exploration - Discover app structure without source code
- ๐ฏ Smart Test Creation - Generate comprehensive test scenarios
How It Worksโ
The Magic Processโ
- Launch Browser - Playwright starts automated browser
- AI Explores - LLM navigates through your application
- Records Actions - Captures clicks, inputs, and validations
- Generates Tests - Creates structured test files
- Iterates - Refines tests based on results
When to Use Playwright MCPโ
Perfect Forโ
- Applications without source code access
- Exploratory testing of complex workflows
- Testing third-party integrations
- User journey validation
- Rapid test prototyping
Alternative Toolsโ
- With source code access โ Use GitHub Copilot for more accurate tests
- API testing โ Consider Database MCP or direct API tools
- Unit testing โ Stick with traditional approaches
Setup and Configurationโ
Project Structureโ
playwright/
โโโ prompts/
โ โโโ generate_tests.md # Context for AI agent
โโโ tests/
โ โโโ login.spec.js
โ โโโ view_report.spec.js
โโโ playwright.config.js
Benefits of Separate Prompts Folderโ
- Reusable contexts for different test types
- Team collaboration on testing strategies
- Documentation of testing approaches
- Version control for prompt improvements
Example Context Promptโ
Create prompts/generate_tests.md:
## Test Generation Context
You are a senior QA engineer specializing in E2E testing with Playwright.
### Requirements:
- Generate comprehensive test scenarios
- Include edge cases and error conditions
- Use descriptive test names and clear assertions
- Follow Page Object Model patterns
### Application Context:
- Login flow uses email/password authentication
- Dashboard contains user-specific data
- Reports section requires special permissions
### Test Priorities:
1. Critical user journeys (login, core features)
2. Error handling (invalid inputs, network issues)
3. Accessibility and performance considerations
Practical Examplesโ
Example 1: Login Flow Testingโ
AI Prompt:
Using Playwright MCP, explore the login functionality and generate
comprehensive test cases covering:
- Valid login credentials
- Invalid email/password combinations
- Password reset flow
- Session management
Generated Test Structure:
// tests/auth/login.spec.js
import { test, expect } from '@playwright/test';
test.describe('Login Flow', () => {
test('successful login with valid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email"]', 'user@example.com');
await page.fill('[data-testid="password"]', 'validPassword');
await page.click('[data-testid="login-button"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('[data-testid="user-menu"]')).toBeVisible();
});
test('login fails with invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email"]', 'invalid@example.com');
await page.fill('[data-testid="password"]', 'wrongPassword');
await page.click('[data-testid="login-button"]');
await expect(page.locator('.error-message')).toContainText('Invalid credentials');
});
});
Example 2: E-commerce Checkoutโ
AI Exploration Result:
// tests/checkout/purchase-flow.spec.js
test('complete purchase flow', async ({ page }) => {
// AI discovered this multi-step workflow
await page.goto('/products');
await page.click('[data-product-id="123"]');
await page.click('button:has-text("Add to Cart")');
await page.click('[data-testid="cart-icon"]');
await page.click('button:has-text("Checkout")');
// Fill shipping information
await page.fill('#shipping-address', '123 Main St');
await page.fill('#city', 'Anytown');
await page.selectOption('#country', 'US');
// Payment flow
await page.fill('#card-number', '4242424242424242');
await page.fill('#expiry', '12/25');
await page.fill('#cvc', '123');
await page.click('button:has-text("Complete Purchase")');
// Verification
await expect(page.locator('.success-message')).toContainText('Order confirmed');
await expect(page).toHaveURL(/\/orders\/\d+/);
});
Advanced Featuresโ
Smart Selector Generationโ
Playwright MCP automatically:
- Prefers
data-testidattributes for stability - Falls back to role-based selectors for accessibility
- Avoids brittle selectors like CSS classes or XPath
- Generates maintainable locators that survive UI changes
Dynamic Content Handlingโ
// AI-generated waiting strategies
await page.waitForLoadState('networkidle');
await expect(page.locator('[data-testid="results"]')).toBeVisible();
await page.waitForFunction(() => document.querySelectorAll('.item').length > 0);
Error Recovery Patternsโ
// AI learns to handle flaky elements
test('robust form submission', async ({ page }) => {
await page.goto('/form');
// Retry mechanism for dynamic forms
await expect(async () => {
await page.fill('#dynamic-field', 'test data');
await page.click('button[type="submit"]');
await expect(page.locator('.success')).toBeVisible();
}).toPass({ timeout: 30000 });
});
Best Practicesโ
โ Do'sโ
- Start with critical user journeys before edge cases
- Use descriptive test names that explain business value
- Let AI iterate on test quality through multiple runs
- Combine with manual review for business logic validation
Don'tsโ
- Don't test every UI detail - Focus on user workflows
- Don't ignore timing issues - Let AI handle waits properly
- Don't test with production data - Use staging environments
- Don't forget mobile testing - Include responsive scenarios
Integration with Other Toolsโ
Combining with GitHub Copilotโ
// Start with Playwright MCP exploration
// Then refine with Copilot for:
// - Better assertions
// - Code organization
// - Error handling
// - Performance optimizations
Database Setup Integrationโ
// Use Database MCP for test data
test.beforeEach(async () => {
// AI can set up test data through Database MCP
await setupTestUser('test@example.com');
await createTestProducts(['product1', 'product2']);
});
Troubleshooting Common Issues ๐งโ
Tests are Flakyโ
// AI learns to add proper waits
await page.waitForLoadState('domcontentloaded');
await expect(page.locator('[data-testid="content"]')).toBeVisible();
Selectors Keep Breakingโ
// AI prefers stable selectors
// โ
Good: data-testid attributes
await page.click('[data-testid="submit-button"]');
// โ Avoid: CSS classes
await page.click('.btn.btn-primary.submit');
Tests Run Too Slowlyโ
// AI optimizes for speed
test.use({
viewport: { width: 1280, height: 720 },
// Skip images and CSS for faster execution
launchOptions: { args: ['--disable-images'] }
});
Next Stepsโ
Ready to enhance your testing workflow further?
- Try TestCraft Extension - UI-focused test generation
- Explore Database MCP - Smart database workflows
- Learn Prompt Engineering - Better AI interactions
Pro Tip
Start with simple page flows before tackling complex multi-step workflows. Let the AI learn your application's patterns gradually! ๐ฏ
Key Takeaways ๐โ
- ๐ญ Playwright MCP combines browser automation with AI intelligence
- ๐ Perfect for exploration when source code isn't available
- ๐ Generates maintainable tests with proper selectors and waits
- ๐ค Complements other tools like GitHub Copilot and Database MCP
Transform your E2E testing with intelligent browser automation! ๐