Playwright Testing: Install, Write, Run, Debug Browser Tests
In this article
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
- Initialize a new Node.js project: Open your terminal, navigate to your project directory, and run
npm init -y. This creates apackage.jsonfile to manage dependencies. - 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). - Install Playwright Test Generator (optional but helpful): Run
npx playwright installto ensure all browsers are properly downloaded. This step is often automatic but ensures no missing binaries. - Create a test directory: Make a folder named
testsin your project root. This is where Playwright expects test files by default. - Write your first test: Inside
tests, create a file calledexample.spec.js. Add the following code:
This test checks the page title and simulates a click on the 'Get started' link.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/); }); - Run the test: In the terminal, run
npx playwright test. Playwright will execute all tests in thetestsfolder using headless mode by default. You’ll see results in the console: passed, failed, or timed out. - View test reports: After running, Playwright generates a report in
playwright-report/. Openindex.htmlin your browser to see a detailed UI report with screenshots and traces. - Run tests in headed mode: To see the browser during execution, run
npx playwright test --headed. This is useful for debugging visual issues. - Debug a test: Use
npx playwright test example.spec.js --debugto 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. - Use trace viewer for deeper analysis: First, enable tracing in your test config. Create
playwright.config.jswith:
Then run tests. If a test fails, usemodule.exports = { use: { trace: 'on-first-retry', }, };npx playwright show-traceto open a detailed timeline of actions, network requests, and DOM snapshots.
Common Mistakes
- Forgetting to await async methods: Playwright uses async/await. Omitting
awaitleads to race conditions and flaky tests. - Using hardcoded waits like
page.waitForTimeout(2000): This makes tests slow and unreliable. Usepage.waitForSelector()or assertions that wait automatically. - Not cleaning up state between tests: Shared browser context or cookies can cause test pollution. Use
test.describefor isolation orpage.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 codegento 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=chromiumto 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.