Playwright End-to-End Testing: Complete Guide Skip to main content
QAonTOP
Contact Us

[ Automation · · 14 min read ]

Mastering Playwright for End-to-End Testing: A Complete Guide for Seamless QA

AUTOMATIONMastering PlaywrightEnd-to-end testing guideQAonTOP

End-to-end (E2E) testing is a full-proof method that ensures an application’s workflow works as intended from start to finish. It tests the integration and interaction of different components, thus finding system modules and data connections dependency. End-to-end testing becomes a very efficient detection method for defects not identified by unit or functional testing, ensuring the expected quality of an application through these stages, which simulate the user environment.

Introducing Playwright

Playwright, which was developed by Microsoft, is a solid open-source framework that is used for web testing and automation. It offers major programming languages like JavaScript, TypeScript, Python, .NET, and Java, and it is suitable for all the major browser engines such as Chromium, Firefox, and WebKit. Playwright’s capabilities include handling modern web features such as native input events, out-of-process iframes, and web workers that make it a versatile E2E testing tool.

Key features of Playwright

  • Supports Chromium, Firefox, and WebKit.
  • Allows test scripting in JavaScript, TypeScript, Python, .NET, and Java.
  • Enables parallel test execution via BrowserStack for efficiency.
  • Works with multiple Chrome, Edge, and Playwright browser versions on Windows and macOS.
  • Captures videos, screenshots, and logs on failure for easy debugging.
  • Offers various element selectors like CSS, text, and XPath element.
  • Uses auto-wait to ensure elements are ready before interaction.
  • Includes Codegen to generate test scripts from user actions (playwright codegen URL).
  • Supports selecting/writing elements via the text content and accessibility labels.
  • Handles shadow DOM, geolocation, permissions, web workers as well as modern web APIs.
  • Supports native input events, iframes, file handling, as well as dark mode.

What is End-to-End Testing?

End-to-end (E2E) testing is a type of software testing that is all about making sure that an app’s entire workflow is working correctly from start to finish. It examines the system dependencies, the behavior of the data, and the correspondence between the components. This is relayed through the application to various servers and databases, so it is always good to run a test to see if all those connections are working properly. It’s all about the user’s perspective, and the main purpose is to make sure that anything and everything on the site and peripheral is working as required.

What is Playwright End-to-End Testing?

Playwright E2E testing lets developers and QAs simulate real user interactions, like clicking buttons, filling out forms, and navigating pages. It automates testing across browsers like Chrome, Firefox, Safari, and Edge, ensuring that expected behaviors work correctly.

Step 1 — Setting up a React demo project

  • Start by cloning the TodoMVC qaOntop React application repository to your local machine:
Terminal
git clone <todomvc-react-repository-url> todo-app

Once you have cloned it, you should go to the project directory and then install the dependencies that are required:

Terminal
cd todo-app
npm install

This step guarantees the availability of all required libraries and tools for the development server. When done with the installation, you shall be able to initiate the server using this command:

Terminal
npm start

The server will initialize and listen on port 8080. The output will resemble:

TerminalILLUSTRATION$ npm start> http-server -p 8080Starting up http-server, serving ./Available on: http://127.0.0.1:8080Hit CTRL-C to stop the server
Development server running on port 8080

For the application to run perfectly, open http://localhost:8080 in your web browser. You should be able to see the TodoMVC application interface. In order to check, add several items to the tasks list and make sure that the application behaves as it should.

localhost:8080ILLUSTRATIONtodosWhat needs to be done?○ Buy groceries○ Write Playwright tests✓ Set up the project2 items left All Active Completed
The TodoMVC app running at http://localhost:8080

With Playwright, you create tests to confirm the principal functions of the app, meaning features like the ability to add and manage to-do items. These tests will validate Playwright as the fastest and simplest way automated browser testing is done.

On completion of the recent task, shut down the development server. Terminate the server by pressing Ctrl-C in the terminal where the server is running. The server will then shut down properly:

Now that the demo project is set up, you’re ready to integrate and configure Playwright for writing and running end-to-end tests.

Step 2 — Setting up Playwright

The next part is the installation of Playwright to your project and setting up the browser engines necessary for end-to-end testing.

To start, make Playwright a part of your project. For this, execute the command below from the root directory of your project:

Terminal
npm init playwright@latest

During the installation, you’ll be prompted to make several selections. Choose as follows for this tutorial:

Installer prompts (example answers)
✔ Do you want to use TypeScript or JavaScript? · JavaScript
✔ Where to put your end-to-end tests? · tests
✔ Add a GitHub Actions workflow? · false
✔ Install Playwright browsers? · true

Once you’re done with this, you’ll be greeted by a message that states the installation is finished and that the playwright and his dependencies are now a part of your project.

TerminalILLUSTRATION$ npm init playwright@latest✔ TypeScript or JavaScript? · TypeScript✔ Where to put your end-to-end tests? · tests✔ Add a GitHub Actions workflow? · false✔ Install Playwright browsers? · trueInstalling Playwright browsers…✔ Success! Created a Playwright Test project
Playwright installation complete

Next, let’s configure Playwright to suit our testing requirements. Open the playwright.config.js file, which was created during the installation, in your preferred text editor:

playwright.config.js
// @ts-check
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  reporter: 'html',
  use: {
    baseURL: 'http://localhost:8080',
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit',   use: { ...devices['Desktop Safari'] } },
  ],
  webServer: {
    command: 'npm start',
    url: 'http://localhost:8080',
    reuseExistingServer: !process.env.CI,
  },
});

One of the main features of the Playwright tool is that users can easily customize their tests. Below are the most important of these features that I talked about in the tutorial:

  • testDir: This option specifies the ./tests directory where one can place all the test files.
  • projects: It sets the targets to the browsers to be used in the testing process (Chromium, Firefox, WebKit).
  • webServer: If you choose Playwright, you can start a local server in your development environment before your test runs. The command property is the shell command that will be executed, and the URL is the root URL of the server after the launch. Read the docs to know more about the available configuration options.
  • use.baseURL: By this way, you’re telling the server the URL of your application root. The use of this feature allows you to see only the relative paths that the test scripts use; they won’t be written as full URLs.

Before the implementation of the playwright script, the package.json file should be created as follows:

package.json (scripts)
"scripts": {
  "start": "webpack serve --port 8080",
  "test:e2e": "playwright test",
  "test:e2e:ui": "playwright test --ui"
}

The script included in this section will create a server configured for Playwright tests with a different port.

Having Playwright installed and set up on any platform is enough to start the writing of your first test script.

Step 3 — Writing your first test

The playwright created a tests directory containing an example test file in the previous step. Start by removing this example:

Project structure
todo-app/
├─ tests/
│  └─ example.spec.js
├─ tests-examples/
├─ playwright.config.js
└─ package.json

Next, create a new test file specifically for your To-do application. This novel test file will create a test that will investigate the application’s state from the beginning. The idea is to validate that when restarting the window, there will be no tasks to be listed, and the input field is in focus.

Feel free to write the code that meets these requirements:

JavaScript
// tests/todo.spec.js
import { test, expect } from '@playwright/test';

test.describe('TodoMVC app', () => {
  test('loads with the correct title', async ({ page }) => {
    await page.goto('/');
    await expect(page).toHaveTitle(/TodoMVC/);
  });
});

The playwright’s test and expect functions are the tools for defining the test and making assertions, respectively. The describe() method, on the other hand, is for grouping related tests and stating clearly what the test suite is about.

In the block of code for the inward describe function, the test() element gives a specific heading to a test case and demonstrates the empty state of a to-do list and the input’s selection.

It will then go to the TodoMVC app by clicking on the http://localhost:8081link. after that,it uses a getByTestId() locator to find elements by data-testid attributes.

The expect() function is subsequently employed to assert that the to-do list is empty and the input field is focused.

To run your test, execute the following command in your terminal:

Terminal
npx playwright test

By using this command, you are starting the development server and having the tests run on different browsers as specified in the playwright.config.js file. To confirm whether the application you are developing behaves as it should in the initial state, all tests must be passed by your browser for the desired results.

TerminalILLUSTRATION$ npx playwright testRunning 3 tests using 3 workers ✓ todo.spec.ts › add a todo (1.2s) ✓ todo.spec.ts › complete a todo (0.9s) ✓ todo.spec.ts › filter active todos (1.1s) 3 passed (3.4s)To open the HTML report run: npx playwright show-report
Test results in the terminal

The section coming up will cover the testing of more sophisticated user interactions now that the application’s initial behavior has been confirmed. In addition, you’ll be exploring how Playwright’s UI mode can help in the understanding and debugging of these interactions.

Step 4 — Exploring Playwright’s UI mode

In this part of the tutorial, you’ll create a test to confirm that items can be successfully added to the to-do app and use Playwright’s UI mode to visualize and debug the test execution.

First, update your todo.spec.js file to include a new test:

JavaScript
const TODO_ITEMS = ['buy groceries', 'book a dentist appointment'];

test('should allow me to add todo items', async ({ page }) => {
  await page.goto('/');
  const newTodo = page.getByPlaceholder('What needs to be done?');

  await newTodo.fill(TODO_ITEMS[0]);
  await newTodo.press('Enter');
  await expect(page.getByTestId('todo-title')).toHaveText([TODO_ITEMS[0]]);

  await newTodo.fill(TODO_ITEMS[1]);
  await newTodo.press('Enter');
  await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS);
});

This test is a way to check if users can add items to the to-do list and ensure that the list updates successfully.

The application loads by typing in the input field for new to-dos using its data-testid and then follows in different stages:

  • The first item in the TODO_ITEMS array is entered into the input field, and the Enter key press is simulated.
  • Verifying the list for its presence of only the first item comes next in the to-do list.
  • The second item from the list of to-do items is entered like the first one.
  • Next, the to-do list is checked again to ensure that it contains both the first and second items

To observe how the test runs, use the following command

Terminal
npx playwright test --ui

When you execute this command, either the Playwright’s UI mode window will be open. This tool lets you interactively step through tests so that you can visually inspect the DOM at different steps, you can view the timeline of test executions, and analyze the action, log, and error in real time. By making it simpler for you to understand, debug, and refine your test scripts, this characteristic of the feature greatly betters the end-to-end testing experience.

Playwright · UI modeILLUSTRATIONTESTStodo.spec.ts ▶ add a todo ▶ complete a todo ▶ filter active todosWatch mode on · Run all ▶
Playwright UI mode

There is a pause in the testing done when the UI mode is activated, initially. The resume button (click on the Play icon next to the test title) is available to continue the process. The test should go on performing the tasks and finish them without making any mistakes.

Playwright · UI mode · pausedILLUSTRATIONPaused at getByPlaceholder("What needs to be done?").fill()▶ Step over ▶▶ ResumeCall log - waiting for getByPlaceholder("What needs to be done?") - locator resolved to <input class="new-todo"> - fill("Buy groceries")
Paused test in UI mode

At the top of the trace, you’ll see a timeline of the test execution. You can hover on any portion of the timeline to see a snapshot of the test or select between two points to filter only the actions and logs for that portion of the test.

Trace viewer · TimelineILLUSTRATION0 ms ─────────────────────────────────────────── 1.2 sgoto http://localhost:8080 120 msfill "Buy groceries" 45 mspress Enter 12 msexpect toHaveCount(1) 30 ms
Trace timeline

The Actions tab shows all test actions with their locators used and the time it took for them to run. By clicking on these actions, their changes can be seen. Furthermore, you can see the application state before and after an action via the Before and After tabs.

Trace viewer · ActionsILLUSTRATIONpage.goto("http://localhost:8080")getByPlaceholder("What needs to be done?").fill("Buy groceries")getByPlaceholder("What needs to be done?").press("Enter")expect(getByTestId("todo-title")).toHaveText("Buy groceries")
Actions tab with locators

If you want to inspect the DOM at any stage of testing, then you will have to click the external link icon positioned on the top right of a DOM snapshot. When you do this, a new window will appear with DevTools settings that will help you examine the problem and be able to correct it.

Trace viewer · DOM snapshotILLUSTRATION<section class="todoapp"> <header class="header"> <h1>todos</h1> <input class="new-todo" placeholder="What needs to be done?"> </header> <ul class="todo-list"> … </ul></section>
DOM snapshot

Below the DOM snapshot, several tabs provide additional information:

  • Locator: Used to select locators from the DOM snapshot that can subsequently be copied into the test script.
  • Source: Shows the code for the highlighted action.
  • Call: Displays timing and locator details.
  • Log: Contains internal Playwright logs.
  • Errors: List any errors encountered during the test.
  • Console and Network: Show application logs and network requests.
  • Attachments: Useful for visual comparisons in regression testing.

To debug and understand the Playwright script behavior more effectively, through the usage of these features, is the way to be sure that they will test the application’s correct functionality.

Step 5 — Detecting visual regressions with Playwright

Visual regression testing aims at locating those inadvertent changes in the visual form of a program. It is a comparison of the current visual settings of all the elements or screens in an application against a bunch of individual images taken before, which is done to ensure that every element in UI renders as it should across various browsers and coding changes.

Playwright provides a comfortable way of checking for visual regressions in your applications by following this general process:

  • Initially, it sets up a collection of images that shows the normal state of the UI elements or pages. Later on, these pictures are the basis for the next comparison.
  • Then, it takes the status of the UI during the test run.
  • It will then contrast these images with the reference. Any mismatches are identified as potential regressions, which could stem from CSS modifications, layout, JavaScript updates, or browser behavior.

Under the hood, Playwright uses the pixelmatch library, a pixel-level image comparison library. When running a visual regression test for the first time, it generates and saves a reference screenshot as the baseline.

Let’s see this in action by adding the following test to your todo.spec.js file:

JavaScript
test('visual regression: empty todo app', async ({ page }) => {
  await page.goto('/');
  await expect(page).toHaveScreenshot();
});

This test uses the toHaveScreenshot() method to capture and compare the current state of the page with the expected baseline image.

Before you execute the test, refactor the test script as shown below:

JavaScript
test.describe('TodoMVC app', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  test('loads with the correct title', async ({ page }) => {
    await expect(page).toHaveTitle(/TodoMVC/);
  });

  test('visual regression: empty todo app', async ({ page }) => {
    await expect(page).toHaveScreenshot();
  });
});

The beforeEach() hook is a directive that a page should be tested. It should be added to a test script page via this line: The beforeEach() hook is a directive that ensures that the page is ready before each test is performed. This will ensure well-organized test scenarios and make sure that the test events will have the correct preconditions before being executed.

Next, go to the command line to run the Visual comparison suite with the command that follows:

Terminal
npx playwright test -g "visual regression"

Initially, the test will fail due to the absence of a baseline image, commonly known as a “golden file“. This failure is expected and part of establishing your initial baseline.

TerminalILLUSTRATION$ npx playwright test visual.spec.ts ✘ visual.spec.ts › home page looks right Error: A snapshot doesn't exist at tests/visual.spec.ts-snapshots/home-chromium.png Writing actual. 1 failed
First run fails because no baseline exists yet

By running the command, an HTML error report will open in your default browser, displaying the failure of the test in all browsers. Such a failure is due to missing baseline images to which comparisons can be made. The report will be a part of a Screenshots section that will contain screenshots of the captured images for viewing.These initial screenshots are the reference images that are saved within your tests directory as follows:

Playwright Test ReportILLUSTRATION✘ home page looks right failedError: A snapshot doesn't existExpected — missing baselineActual home-chromium-actual.pngRun again with --update-snapshots to create it.
HTML report showing the missing baseline

Each reference file’s name is a series of the suite name, test name, browser engine, and platform, all concatenated. Moreover, by passing an argument to toHaveScreenshot(), you can also custom-create a screenshot name:

Naming pattern
<test-name>-<project>-<platform>.png

This will yield file names such as:

Generated snapshot files
tests/todo.spec.js-snapshots/
  visual-regression-empty-todo-app-1-chromium-linux.png
  visual-regression-empty-todo-app-1-firefox-linux.png
  visual-regression-empty-todo-app-1-webkit-linux.png

As soon as you have a Playwright setup running, which means an initial screenshot is established, every time you run a test it will compare the one captured from the UI with this baseline reference.

Stop the HTML report server by pressing Ctrl-C, then execute the visual regression test again in the same way as follows:

Terminal
npx playwright test -g "visual regression"

You should see a successful test run, indicating no visual discrepancies:

TerminalILLUSTRATION$ npx playwright test visual.spec.tsRunning 1 test using 1 worker ✓ visual.spec.ts › home page looks right (2.1s) 1 passed (2.4s)
Visual test passing against the baseline

For showcasing Playwright’s ability to create visual regression reports, you may want to affect the change of a small part of your app. For instance, change the color of a header element in the file called header.jsx:

CSS change used to trigger a regression
/* src/index.css */
.todoapp h1 {
  color: #0B4FD8; /* was the original header colour */
}

The header’s text color of the blend between beta and blue has been modulated, trying to resemble a meander’s color change.

Perform the visual regression test again:

Terminal
npx playwright test -g "visual regression"

This time, expect the test to fail as the UI’s current state deviates from the baseline:

TerminalILLUSTRATION$ npx playwright test visual.spec.ts ✘ visual.spec.ts › home page looks right Error: Screenshot comparison failed: 1,284 pixels (ratio 0.01) are different. Expected: home-chromium.png Received: home-chromium-actual.png Diff: home-chromium-diff.png
Visual test failing after the change

When the anyhow test fails, the report pops up in your browser and then shows the specifics:

Playwright Test Report · Image mismatchILLUSTRATIONDiff Actual Expected Side by side SliderChanged pixels are highlighted in red on the diff image1,284 pixels differ (ratio 0.01)
Image mismatch view in the report

Open any of the failed items and slide down to the Image mismatch section to contrast the new screenshot and the reference.

  • Diff delineates the changed areas with red,
  • Actual shows the latest snapshot,
  • Expected shows the original screenshot,
  • Side by side shows the expected and actual results side by side,
  • The slider affords a fun, interactive method of finding the differences by dragging a slider.

Dealing especially with a test problem, the fundamental rules boil down to the following two:

  • Accidental modifications: When you find out that the appearance has changed without your intention, you should find the cause of the problem and then change or fix the code until everything passes the test.
  • Planned upgrades: When the system is fixed, users should use the sikuli-click command to get the new reference screenshot for the page where the changes happened, as follows:
Terminal
npx playwright test --update-snapshots

It regenerates the baseline images, aligning them with the new visual state of your application:

When the basic images are updated, the assessments will pass, showing the new approved condition of the UI. The corrected screenshots are then saved to the source control to become the new reference for future tests.

Playwright compared with Selenium and Cypress

All three are capable tools; Playwright stands out for speed, auto-waiting and built-in tracing.
AspectPlaywrightSeleniumCypress
BrowsersChromium, Firefox, WebKitAll major browsers via driversChromium family, Firefox, WebKit (experimental)
LanguagesJS/TS, Python, Java, .NETJava, Python, C#, JS, Ruby and moreJavaScript/TypeScript
Auto-waitingBuilt inManual waits neededBuilt in
Multiple tabs and originsSupportedSupportedLimited
Parallel runsBuilt in, freeVia Selenium GridPaid dashboard or plugins
DebuggingUI mode, trace viewerDepends on toolingTime-travel runner

Best practices for reliable Playwright tests

  1. 1Prefer user-facing locatorsUse getByRole, getByLabel and getByText before CSS or XPath, so tests survive markup changes.
  2. 2Never use fixed sleepsRely on auto-waiting and web-first assertions like toBeVisible() instead of waitForTimeout().
  3. 3Keep tests independentEach test should create its own data and not depend on another test running first.
  4. 4Log in once, reuse the sessionSave authentication state in a setup project and reuse it, instead of logging in through the UI in every test.
  5. 5Use the Page Object pattern for larger suitesGroup locators and actions per page so changes are made in one place.
  6. 6Run in CI with traces on retryKeep trace: "on-first-retry" so every flaky failure comes with a full recording.
Page Object example (tests/pages/todo-page.js)
export class TodoPage {
  constructor(page) {
    this.page = page;
    this.newTodo = page.getByPlaceholder('What needs to be done?');
    this.items = page.getByTestId('todo-title');
  }
  async goto() { await this.page.goto('/'); }
  async add(text) {
    await this.newTodo.fill(text);
    await this.newTodo.press('Enter');
  }
}

// In a test:
// const todo = new TodoPage(page);
// await todo.goto();
// await todo.add('buy milk');
// await expect(todo.items).toHaveText(['buy milk']);

[ Playwright E2E readiness checklist ]

  • Config sets baseURL, webServer and the browsers you support
  • Critical user journeys covered, each in an independent test
  • Locators use roles, labels or test IDs rather than fragile CSS
  • Visual baselines generated in the same OS as CI
  • Traces and screenshots captured on failure
  • Tests run in CI on every pull request, in parallel
  • Flaky tests tracked and fixed, not just retried

Final thoughts

In this article, you have seen how to write, run, and debug end-to-end tests for a React app using Playwright. We also talked about the role of regression testing in preserving the visual consistency of application frontends and showed how these tests can be implemented efficiently.

For further details and expert QA solutions, visit qoantop—your go-to partner for smooth and high-quality software testing.

Thanks for reading, and stay tuned!

[ Key takeaways ]

  • Playwright runs fast, reliable E2E tests across Chromium, Firefox and WebKit from one API.
  • The webServer and baseURL options let tests start and target your app automatically.
  • UI mode and the trace viewer make debugging failures much faster.
  • toHaveScreenshot() adds visual regression testing with almost no extra setup.
  • User-facing locators, independent tests and CI traces keep suites stable over time.

Frequently asked questions

Is Playwright free?

Yes. Playwright is open source and free, including its test runner, parallel execution, UI mode and trace viewer.

Is Playwright better than Selenium?

For modern web apps, Playwright is often faster to write and more stable thanks to auto-waiting and built-in tooling. Selenium remains useful for its broad language support and large ecosystem.

Can Playwright test mobile apps?

Playwright can emulate mobile browsers, including viewport, touch and user agent. Native iOS and Android apps need tools such as Appium.

How do I update visual snapshots in Playwright?

Run npx playwright test --update-snapshots after confirming the visual change is intended. Commit the new baseline images with the code change.

Why do visual tests fail in CI but pass locally?

Fonts and rendering differ between operating systems. Generate and compare baselines in the same environment as CI, for example using the official Playwright Docker image.

How do you run Playwright in CI?

You run Playwright in CI by adding it to your pipeline. When you install Playwright, it offers to add a GitHub Actions workflow and install the browsers, so your end-to-end tests run on every change. Keep tests independent, use user-facing locators and collect CI traces so failures are easy to debug.

Let’s discuss the opportunities

Talk to QAonTOP

More from the blog

Your dev team needs a solid QA partner

Free one-week POCNDA before accessA QA lead replies the same working day