🔍 Playwright Debugging Basics: Your Detective Toolkit
Imagine you’re a detective solving a mystery. Your tests are like witnesses telling you what happened. But sometimes witnesses get confused! That’s when you need your detective tools to find the truth.
🎯 What is Debugging?
Debugging = Finding and Fixing Bugs
Think of it like this:
- Your test is a robot following instructions
- Sometimes the robot gets stuck or confused
- Debugging helps you see EXACTLY what the robot sees
- Then you can fix the problem!
Real Life Example:
- You tell your friend to “go to the red house”
- They can’t find it… why?
- Maybe the house is ORANGE, not red!
- Debugging = watching your friend’s journey to see where they got lost
🚀 The 5 Detective Tools
graph TD A["🔍 Debugging Tests"] --> B["🚩 Debug Mode Flag"] A --> C["🔬 Playwright Inspector"] A --> D["⏸️ page.pause"] A --> E["📝 Console Logging"]
1️⃣ Debugging Tests: The Big Picture
What Does It Mean?
When your test fails, you need to figure out WHY. It’s like when a recipe goes wrong - you need to check each step!
Simple Example
// Your test says "click the blue button"
await page.click('.blue-button');
// But wait... is there even a
// blue button on the page?
// Debugging helps you SEE the page!
Why Tests Fail (Common Reasons)
| Problem | What Happened |
|---|---|
| Element not found | Button doesn’t exist yet |
| Wrong selector | Looking for wrong thing |
| Timing issue | Page too slow |
| Page changed | Website got updated |
2️⃣ Debug Mode Flag: The Slow-Motion Button
The Analogy
Imagine watching a soccer goal. It happens SO fast! But with slow-motion replay, you see every detail. Debug mode = slow-motion for your tests.
How to Use It
Method 1: Command Line
npx playwright test --debug
Method 2: In Your Code
// Add this to playwright.config.js
export default {
use: {
headless: false,
slowMo: 1000 // 1 second pause
}
}
What Happens?
| Normal Mode | Debug Mode |
|---|---|
| Runs invisible | Opens real browser |
| Super fast | Slow and visible |
| Hard to see | Easy to watch |
Pro Tip 🌟
# Debug just ONE test file
npx playwright test login.spec.ts --debug
3️⃣ Playwright Inspector: Your Magnifying Glass
The Story
You’re exploring a new city. The Inspector is like having a local guide who can:
- Show you exactly where you are
- Point at any building and tell you its name
- Help you pick the right path
How to Launch It
npx playwright test --debug
This opens TWO windows:
- The Browser - showing your website
- The Inspector - your control panel
What Can You Do?
graph TD A["Inspector Window"] --> B["▶️ Step Through"] A --> C["🎯 Pick Locator"] A --> D["📊 See Actions"] A --> E["🔄 Record New Steps"]
Pick Locator Feature
The Most Magical Part!
- Click the “Pick Locator” button
- Hover over any element on page
- Inspector shows you the BEST way to find it!
// Inspector might suggest:
page.getByRole('button', { name: 'Submit' })
// Instead of fragile:
page.locator('#btn-123-xyz')
Example Workflow
// Step 1: You wrote this
await page.click('#login');
// Step 2: It fails! Open Inspector
// Step 3: Use Pick Locator
// Step 4: Find better selector
await page.getByRole('button',
{ name: 'Log In' }
);
4️⃣ page.pause(): The Freeze Frame
The Analogy
Playing a video game and need a bathroom break? Hit PAUSE! page.pause() does exactly that for your tests.
How to Use It
test('check shopping cart', async ({ page }) => {
await page.goto('https://shop.example.com');
await page.click('.add-to-cart');
// FREEZE! Let me look around
await page.pause();
// Test continues after you click
// "Resume" in Inspector
await page.click('.checkout');
});
When to Use It
| Situation | Add pause() HERE |
|---|---|
| Test fails mysteriously | Before the failing line |
| Need to check page state | After page loads |
| Want to try selectors | Before clicking elements |
Multiple Pauses
await page.goto('/products');
await page.pause(); // Check #1
await page.click('.filter');
await page.pause(); // Check #2
await page.click('.buy');
await page.pause(); // Check #3
Removing Pauses
Important! Remove page.pause() before running in CI/CD. It will wait forever!
// For production, remove or comment out:
// await page.pause();
5️⃣ Console Logging: Leave Breadcrumbs
The Story
Hansel and Gretel left breadcrumbs to find their way home. console.log() leaves breadcrumbs in your code!
Basic Usage
test('user signup', async ({ page }) => {
console.log('Starting signup test');
await page.goto('/signup');
console.log('Page loaded');
const title = await page.title();
console.log('Page title:', title);
await page.fill('#email', 'test@example.com');
console.log('Email filled');
});
Output Example
Starting signup test
Page loaded
Page title: Sign Up - MyApp
Email filled
Advanced Logging Tricks
Log Current URL:
console.log('URL:', page.url());
Log Element Count:
const buttons = page.locator('button');
console.log('Buttons found:',
await buttons.count()
);
Log Element Text:
const heading = page.locator('h1');
console.log('Heading says:',
await heading.textContent()
);
Pretty Logging
// Add emojis for easy scanning!
console.log('✅ Login successful');
console.log('❌ Button not found');
console.log('⏳ Waiting for element...');
console.log('🎯 Found target:', selector);
🛠️ Putting It All Together
The Complete Detective Workflow
graph TD A["Test Fails"] --> B{What to do?} B --> C["Add console.log"] C --> D["Run with --debug"] D --> E["Use Inspector"] E --> F["Add page.pause"] F --> G["Find the bug!"] G --> H["Fix and celebrate! 🎉"]
Real Debugging Session
test('buy product', async ({ page }) => {
console.log('🚀 Starting test');
await page.goto('https://shop.example.com');
console.log('📄 Page loaded:', page.url());
// This line fails! Let's investigate
await page.pause(); // FREEZE HERE
const buyBtn = page.getByRole('button',
{ name: 'Buy Now' }
);
console.log('🔍 Button exists?',
await buyBtn.count() > 0
);
await buyBtn.click();
console.log('✅ Clicked successfully!');
});
📋 Quick Command Reference
| What You Want | Command |
|---|---|
| Debug all tests | npx playwright test --debug |
| Debug one file | npx playwright test file.spec.ts --debug |
| Debug one test | npx playwright test -g "test name" --debug |
| Show browser | npx playwright test --headed |
| Slow down | Add slowMo: 1000 to config |
🎯 Summary: Your 5 Tools
| Tool | What It Does | When to Use |
|---|---|---|
| Debug Flag | Opens browser, slows down | Start here |
| Inspector | Visual control panel | Pick selectors |
| page.pause() | Freezes test | Check specific spot |
| console.log() | Prints messages | Track progress |
| Combinations | Use them together! | Complex bugs |
🌟 You’ve Got This!
Remember:
- Every bug is solvable
- Use your tools step by step
- Start simple, then dig deeper
- The Inspector is your best friend
You’re not just writing tests anymore. You’re a debugging detective with the best toolkit in town! 🕵️♂️
Next time your test fails, don’t panic. Grab your magnifying glass (Inspector), hit slow-motion (debug flag), freeze the action (page.pause), and follow the breadcrumbs (console.log). The bug doesn’t stand a chance! 🐛🔍
