ThisCalculator

Everyday

Playwright UI Testing: A Beginner’s Step-by-Step Guide

Updated · Standard formula, shown below

Playwright UI Testing: A Beginner's Step-by-Step Guide

This guide walks you through setting up automated UI testing from scratch using Playwright, a modern browser automation tool. You’ll learn how to install Playwright, write your first test, run it, and integrate it into your workflow. By the end, you’ll have a working test suite that can verify your web application’s functionality across multiple browsers.

What You’ll Need

  • Node.js (version 16 or later) installed on your machine. You can download it from the official Node.js website.
  • A code editor (like VS Code, Sublime Text, or any other you prefer).
  • Basic familiarity with JavaScript or TypeScript syntax (Playwright supports both).
  • A web application to test (it can be a local development server or a public URL).

Step-by-Step

  1. Initialize a new Node.js project
    Open your terminal, create a new folder for your test project, and navigate into it. Run npm init -y to create a package.json file with default settings.
  2. Install Playwright
    Run npm install -D @playwright/test to install Playwright’s test runner. Then run npx playwright install to download the browser binaries (Chromium, Firefox, WebKit). This may take a few minutes depending on your internet speed.
  3. Create a test file
    Create a new folder called tests in your project root. Inside it, create a file named example.spec.js. This is where you’ll write your first test.
  4. Write your first test
    Open the file and add the following code:
    const { test, expect } = require('@playwright/test');
    
    test('Page title is correct', async ({ page }) => {
      await page.goto('https://example.com');
      await expect(page).toHaveTitle('Example Domain');
    });

    This test navigates to a URL and checks that the page title matches the expected value.

  5. Run the test
    In the terminal, run npx playwright test. Playwright will run the test in headless mode (no browser window) and show you the results in the terminal. If the test passes, you’ll see a green checkmark.
  6. Run tests with a visible browser
    To see what’s happening during the test, run npx playwright test --headed. This opens a browser window so you can watch the test execute.
  7. Add more assertions
    Playwright provides many assertions. For example, to check that a button is visible and clickable, you can use:
    await expect(page.locator('button.submit')).toBeVisible();
    await page.click('button.submit');

    Explore the Playwright API docs to find more.

  8. Use fixtures for setup
    If you need to log in before each test, you can use a beforeEach hook. For example:
    test.beforeEach(async ({ page }) => {
      await page.goto('https://example.com/login');
      await page.fill('#username', 'testuser');
      await page.fill('#password', 'password');
      await page.click('button[type="submit"]');
    });

    This runs before each test in the file.

  9. Run tests in multiple browsers
    By default, Playwright runs tests in Chromium. To run in Firefox and WebKit too, create a playwright.config.js file at the project root with:
    module.exports = {
      projects: [
        { name: 'chromium', use: { browserName: 'chromium' } },
        { name: 'firefox', use: { browserName: 'firefox' } },
        { name: 'webkit', use: { browserName: 'webkit' } },
      ],
    };

    Then run npx playwright test again. It will run your tests in all three browsers.

  10. Generate a test report
    After running tests, Playwright generates an HTML report by default. To view it, run npx playwright show-report after the test run. This opens a detailed report in your browser showing pass/fail status, test duration, and screenshots on failure.

Common Mistakes

  • Not using proper selectors – Using fragile selectors like #main-content > div > button can break when the DOM changes. Prefer getByRole, getByText, or data-testid attributes.
  • Ignoring waits – Playwright auto-waits for elements to be actionable, but if you use page.waitForTimeout() excessively, it slows down tests and can cause flakiness. Use explicit waits like expect(locator).toBeVisible() instead.
  • Running tests in parallel without isolation – If tests share state (like a database), running them in parallel can cause conflicts. Use Playwright’s fixtures to set up and tear down data per test.
  • Not using the test runner – Writing raw scripts with playwright.chromium.launch() instead of using the test runner misses out on features like fixtures, parallelism, and reporting.

Tips

  • Use data-testid attributes in your app’s HTML to make selectors stable and independent of styling or structure.
  • Take advantage of Playwright’s trace viewer by adding trace: 'on-first-retry' in your config. It records a full trace of the test, including network requests and console logs, which is invaluable for debugging.
  • Use test.describe to group related tests and share setup/teardown logic.
  • Run a single test with npx playwright test --grep "test name" to save time during development.
  • Keep your tests independent – each test should be able to run alone and in any order. Use test.beforeEach to reset state.

Troubleshooting

  • Tests fail with “Error: browserType.launch: Executable doesn’t exist” – This means the browser binaries are not installed. Run npx playwright install again, and ensure you have internet access.
  • Tests are slow – Check if you’re using page.waitForTimeout() excessively. Also, consider running tests in parallel by setting fullyParallel: true in your config (default in newer versions).
  • Element not found – If a selector fails, use page.locator('your-selector').count() to see how many elements match. Also, try using page.pause() to open the Playwright Inspector and debug interactively.
  • Test passes locally but fails in CI – This often happens due to missing system dependencies for browsers in the CI environment. Run npx playwright install-deps on your CI machine (Linux) to install required libraries.
  • Cannot run on Windows with WebKit – Playwright’s WebKit on Windows may have limitations. Use a Linux or macOS environment for full WebKit support, or rely on Chromium and Firefox.

Frequently Asked Questions

Do I need to write tests in JavaScript?

No, Playwright supports TypeScript out of the box. You can write tests in .spec.ts files and use type checking for better code quality.

Can I test a website that requires authentication?

Yes. You can either log in within a beforeEach hook, or use Playwright’s storage state feature to save cookies and reuse them across tests.

How do I take screenshots on failure?

By default, Playwright captures a screenshot when a test fails. You can also manually capture screenshots using await page.screenshot({ path: 'screenshot.png' }).

Can I run tests on a real mobile device?

Playwright can emulate mobile devices by setting the viewport and user agent. For real device testing, you’d need a separate cloud service, but for most UI testing, emulation is sufficient.

How do I run a single test file?

Use npx playwright test tests/example.spec.js to run a specific file. You can also use --grep to filter by test name.

Is Playwright free to use?

Yes, Playwright is open-source and free. You only need to pay if you use a cloud service for parallel execution, but you can run tests locally for free.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.