Logo

dev-resources.site

for different kinds of informations.

Debugging Playwright Tests Like a Pro

Published at
12/26/2024
Categories
playwright
typescript
testing
webdev
Author
aswani25
Author
8 person written this
aswani25
open
Debugging Playwright Tests Like a Pro

Table of Contents

Introduction

Debugging is an essential skill for any developer, especially when working with automated tests. Playwright, with its powerful debugging features, makes it easier to identify and fix issues in your tests. In this post, we’ll explore various techniques and tools to debug Playwright tests effectively and ensure your test suite runs smoothly.

1. Using Playwright's Built-in Debugging Tools

Playwright provides several built-in features to help debug tests:

a. --debug Mode

Run your tests in debug mode to pause on errors and interact with the browser manually.

npx playwright test --debug
Enter fullscreen mode Exit fullscreen mode

This mode launches the browser in a non-headless state and opens Playwright Inspector, allowing you to step through your test code.

b. Playwright Inspector
Playwright Inspector is an interactive tool that lets you:

  • Step through test execution.
  • Highlight elements on the page.
  • View the current state of the DOM.

Enable the inspector in your code:

const { test } = require('@playwright/test');

test('example test', async ({ page }) => {
  await page.pause(); // Launches Playwright Inspector
  await page.goto('https://example.com');
  await page.click('#button');
});
Enter fullscreen mode Exit fullscreen mode

c. Slow-Motion Mode

Run tests in slow motion to observe every step.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false, slowMo: 100 });
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.click('#button');
  await browser.close();
})();
Enter fullscreen mode Exit fullscreen mode

2. Enhanced Logging

a. Debug Logs

Enable debug logs to get detailed information about test execution.

DEBUG=pw:api npx playwright test
Enter fullscreen mode Exit fullscreen mode

This logs all Playwright API calls, helping you understand what’s happening during the test.

b. Custom Logging

Add custom logs in your tests to track variable values and execution flow:

console.log('Navigating to example.com');
await page.goto('https://example.com');
console.log('Clicked the button');
await page.click('#button');
Enter fullscreen mode Exit fullscreen mode

3. Screenshots and Videos

Capture screenshots and videos to review what happened during test execution.

a. Capture on Failure

Configure Playwright to take screenshots or record videos on test failure:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
});
Enter fullscreen mode Exit fullscreen mode

b. Manual Screenshots

Take screenshots at specific points in your test:

await page.screenshot({ path: 'screenshot.png' });
Enter fullscreen mode Exit fullscreen mode

4. Debugging with Breakpoints

a. Use Breakpoints in IDEs

If you’re using an IDE like VS Code, set breakpoints in your test code and run Playwright tests in debug mode:

  1. Add a debugger statement in your test:
debugger;
Enter fullscreen mode Exit fullscreen mode
  1. Launch the debugger in VS Code. b. Attach to Node.js

Use Node.js debugging tools to attach to the test process:

node --inspect-brk node_modules/.bin/playwright test
Enter fullscreen mode Exit fullscreen mode

5. Analyzing Network and Console Logs

a. Capture Network Traffic

Intercept and analyze network requests to debug API interactions:

page.on('request', request => console.log('Request:', request.url()));
page.on('response', response => console.log('Response:', response.url()));
Enter fullscreen mode Exit fullscreen mode

b. Listen to Console Logs

Capture and print console logs from the browser:

page.on('console', msg => console.log('Console log:', msg.text()));
Enter fullscreen mode Exit fullscreen mode

6. Handling Flaky Tests

Flaky tests can be challenging to debug. Here’s how to tackle them:

a. Retry Failed Tests

Enable retries to catch intermittent failures:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  retries: 2,
});
Enter fullscreen mode Exit fullscreen mode

b. Debug Specific Tests

Run a single test with debugging enabled:

npx playwright test --project=chromium --grep "test name"
Enter fullscreen mode Exit fullscreen mode

c. Use Test Hooks

Add hooks to log additional information during flaky tests:

test.beforeEach(async ({ page }) => {
  console.log('Starting test');
});

test.afterEach(async ({ page }) => {
  await page.screenshot({ path: `test-failure.png` });
});
Enter fullscreen mode Exit fullscreen mode

7. Best Practices for Debugging

  1. Reproduce Issues Locally: Run tests locally with the same configuration as your CI environment.
  2. Check Dependencies: Ensure all browser versions and Playwright dependencies are up to date.
  3. Isolate Tests: Run tests individually to isolate issues.
  4. Analyze Reports: Use HTML test reports to trace failures.

Conclusion

Debugging Playwright tests doesn’t have to be a daunting task. With features like Playwright Inspector, detailed logging, and network analysis, you can quickly identify and resolve issues. By adopting these debugging techniques, you’ll not only save time but also improve the reliability of your test suite.

What’s your favorite Playwright debugging tip? Share it in the comments below!

playwright Article's
30 articles in total
Favicon
Creating Open Graph Images in Django for Improved Social Media Sharing
Favicon
Cypress Debugging: How to Get Started
Favicon
Automating Visual Regression Testing with Playwright
Favicon
Testing with Playwright: Use i18next Translations in Tests, but not `t('key')`
Favicon
"Fix with AI" Button in Playwright HTML Report
Favicon
How to choose e2e automation framework 🩺 for your project
Favicon
My First Steps with Playwright 🎭: A Tester’s Journey from Selenium
Favicon
Playwright
Favicon
Enhance Your Playwright Skills: Mastering Page Load Waits
Favicon
Let's check it out!
Favicon
Playwright vs Selenium WebDriver: Simplified. Which one to choose for your application automation needs?
Favicon
Choose The Reliable MBA Assignment Help With These Top 10 Tips: A Comprehensive Guide!
Favicon
Why is My Multi-Threaded API Still Slow?
Favicon
Comparing Test Execution Speed of Modern Test Automation Frameworks: Cypress vs Playwright
Favicon
Playwright java is unable to open browser in incognito window
Favicon
Supercharge Your E2E Tests with Playwright and Cucumber Integration
Favicon
Automating UI Testing: Building a Robust Framework with Playwright, Java, Docker, and CI/CD
Favicon
2025 New Book Launched !Web Automation Testing with Playwright
Favicon
Christmas Magic Tiles
Favicon
Playwright vs Selenium: A Detailed Comparison
Favicon
Integrating Playwright with CI/CD Pipelines using GitLab: A Step-by-Step Guide
Favicon
End-to-End API Testing with Playwright
Favicon
Testing in Incognito Mode with Playwright
Favicon
Cross-Browser Testing Made Easy with Playwright
Favicon
Playwright Test Best Practices for Scalability
Favicon
Debugging Playwright Tests Like a Pro
Favicon
How to Use Playwright Locators: A Detailed Guide
Favicon
Advanced Playwright Features: Beyond the Basics
Favicon
Creating an Effective Test Automation Strategy: Your Guide to Success
Favicon
Getting Started with Playwright: A Step-by-Step Guide

Featured ones: