User Agents

Web browsers and everyday web tech, explained

Playwright Testing: Install, Write, Run, Debug Browser Tests

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Playwright is a powerful, modern browser automation library for running fast, reliable end-to-end tests across Chromium, Firefox, and WebKit. It enables developers to simulate user interactions, validate UI behavior, and catch regressions early. This guide walks you through installing Playwright, writing your first browser test, running it, and debugging when things go wrong—all using real-world, actionable steps.

What You'll Need

  • Node.js (version 14 or higher) installed on your system
  • A code editor (VS Code recommended)
  • Terminal access (Command Prompt, PowerShell, or Bash)
  • An active internet connection to download Playwright and browsers

Step-by-Step

  1. Initialize a new Node.js project: Open your terminal, navigate to your project directory, and run npm init -y. This creates a package.json file to manage dependencies.
  2. Install Playwright: Run npm install @playwright/test --save-dev. This adds Playwright as a development dependency and installs the required browser binaries (Chromium, Firefox, WebKit).
  3. Install Playwright Test Generator (optional but helpful): Run npx playwright install to ensure all browsers are properly downloaded. This step is often automatic but ensures no missing binaries.
  4. Create a test directory: Make a folder named tests in your project root. This is where Playwright expects test files by default.
  5. Write your first test: Inside tests, create a file called example.spec.js. Add the following code:
    const { test, expect } = require('@playwright/test');
    
    test('has title', async ({ page }) => {
      await page.goto('https://playwright.dev');
      await expect(page).toHaveTitle(/Playwright/);
    });
    
    test('gets started link', async ({ page }) => {
      await page.goto('https://playwright.dev');
      await page.click('text=Get started');
      await expect(page).toHaveURL(/intro/);
    });
    
    This test checks the page title and simulates a click on the 'Get started' link.
  6. Run the test: In the terminal, run npx playwright test. Playwright will execute all tests in the tests folder using headless mode by default. You’ll see results in the console: passed, failed, or timed out.
  7. View test reports: After running, Playwright generates a report in playwright-report/. Open index.html in your browser to see a detailed UI report with screenshots and traces.
  8. Run tests in headed mode: To see the browser during execution, run npx playwright test --headed. This is useful for debugging visual issues.
  9. Debug a test: Use npx playwright test example.spec.js --debug to launch the interactive debugger. This opens a browser window with dev tools, pauses on each action, and lets you step through the test line by line.
  10. Use trace viewer for deeper analysis: First, enable tracing in your test config. Create playwright.config.js with:
    module.exports = {
      use: {
        trace: 'on-first-retry',
      },
    };
    
    Then run tests. If a test fails, use npx playwright show-trace to open a detailed timeline of actions, network requests, and DOM snapshots.

Common Mistakes

  • Forgetting to await async methods: Playwright uses async/await. Omitting await leads to race conditions and flaky tests.
  • Using hardcoded waits like page.waitForTimeout(2000): This makes tests slow and unreliable. Use page.waitForSelector() or assertions that wait automatically.
  • Not cleaning up state between tests: Shared browser context or cookies can cause test pollution. Use test.describe for isolation or page.context().clearCookies() when needed.
  • Writing brittle selectors: Avoid overly specific CSS paths. Use text, role, or label-based locators like getByRole('button', { name: 'Submit' }) for resilience.
  • Ignoring mobile emulation: Playwright supports device emulation. Failing to test mobile views can miss responsive issues.

Tips

  • Use the Code Generator: Run npx playwright codegen to record user actions and auto-generate test code. Great for learning syntax or building complex flows quickly.
  • Leverage test.describe for grouping: Organize related tests using test.describe('Login flow', () => { ... }) for better readability and setup/teardown logic.
  • Run tests in multiple browsers: By default, Playwright runs in all three browsers. Disable unwanted ones in config or use --project=chromium to target one.
  • Take screenshots on failure: Enable screenshot: 'on' in config to automatically capture visuals when a test fails.
  • Use test.setTimeout() sparingly: Increase timeout only when necessary, such as for slow API responses. Default is 30 seconds.

Troubleshooting

If tests fail unexpectedly, start by running in --headed mode to observe behavior. Check for network issues or slow page loads. If Playwright fails to launch browsers, run npx playwright install to reinstall binaries. For missing elements, verify selectors using Playwright Inspector via --debug. If tests pass locally but fail in CI, ensure CI environment has proper display settings or use Docker images with PLAYWRIGHT_BROWSERS_PATH=1. Always review trace reports—they often reveal timing issues or incorrect expectations.

Frequently Asked Questions

Can Playwright test mobile views?

Yes. Use built-in device descriptors like iPhone 13 in playwright.config.js to emulate mobile browsers and test responsive design.

Does Playwright support single-page applications (SPAs)?

Yes. Playwright handles dynamic content, client-side routing, and JavaScript-heavy apps effectively, making it ideal for React, Vue, and Angular.

How is Playwright different from Puppeteer?

Playwright supports multiple browsers (not just Chromium), has built-in auto-waiting, cross-browser coverage, and better mobile emulation compared to Puppeteer.

Can I run Playwright tests in CI/CD pipelines?

Yes. Playwright integrates with GitHub Actions, GitLab CI, and others. Use official Docker images or install dependencies in your pipeline.

Why does my test pass locally but fail in CI?

Common causes include timing issues, missing browser dependencies, or lack of GPU. Run with --video and trace: 'on' to diagnose.

How do I test file uploads?

Use page.setInputFiles('input[type=file]', ['/path/to/file.pdf']) to simulate file selection during tests.