Playwright For Test Automation: A Step by Step Guide

playwright test automation

Summarize this blog post with:

Playwright is a powerful and versatile automation library developed by Microsoft in 2020. It enables developers and testers to automate web applications across multiple browsers with ease. The framework has earned 83.6k stars and 5.2k forks on GitHub, with detailed documentation available on the same platform to help you get started quickly.

This guide will walk you through the basics of using Playwright for test automation, from installation to writing and running your first tests. Playwright automation supports Chromium, Firefox, and WebKit, allowing you to test across different browsers seamlessly.

In this blog, we will deep dive into the various features of Playwright and how we can perform end-to-end testing with Playwright with detailed examples. But before we do that, let’s first understand what Playwright actually is and what it does.

TL;DR

  • Playwright testing allows teams to validate user interactions across Chromium, Firefox, and WebKit, making cross-browser testing easier with a single automation framework.
  • The Playwright testing framework includes built-in capabilities such as automatic waiting, network interception, and powerful selectors, which help reduce flaky tests and improve execution reliability.
  • Playwright automation testing supports multiple programming languages, including JavaScript, TypeScript, Python, Java, and C#, giving development and QA teams flexibility in writing test scripts.
  • With features like parallel execution, browser context isolation, and headless execution, Playwright test automation helps teams run faster and more scalable test suites.
  • Developers can learn Playwright through structured tutorials and automation examples, making it easier to adopt Playwright automation for modern web applications.
  • As a modern Playwright automation tool, the framework integrates easily with CI/CD pipelines and cloud testing platforms to support scalable automated testing workflows.

What Is Playwright?

Simply put, it’s an open-source browser automation framework created by Microsoft for testing modern web apps.

Playwright basically equips developers and QA teams to simulate real user interactions, such as clicking buttons, navigating pages, filling forms, and validating app behavior across multiple browsers. It works across WebKit, Firefox, and Chromium.

In Playwright testing, you always have a consistent API to run tests on different browsers without the need to rewrite scripts.

How Does Playwright Testing Work?

The Playwright testing framework makes use of a layered architecture to connect test scripts to browser engines via a communication protocol. Let’s see how the process works:

1. Create the test script: You write Playwright automation scripts in languages such as Typescript, Python, C#, Java, and JavaScript. These scripts define actions, like clicking elements, capturing network activity, or navigating pages.

2. Playwright client sends commands: When tests run, the scripts communicate with a Playwright server (Node.js) using a WebSocket connection. The server receives the commands and translates them into instructions the browser can execute.

3. Driver communicates with browser engines: Playwright interacts with Chromium, Firefox, and WebKit using browser-specific automation protocols such as the Chrome DevTools Protocol. This enables the browser to perform the requested actions, such as loading pages and interacting with elements.

4. Results return to the test script: In the end, the browser returns execution results to the Playwright driver, which sends them back to the test script. Assertions then verify whether or not the app behaved as expected.

Key Features of Playwright

Below are some of the key features of the Playwright testing tool

1. Cross-browser Testing: Playwright supports all major browsers out of the box, including Chromium, Firefox, and WebKit (Safari). This cross-browser support allows you to write tests once and run them across multiple browsers without any additional configuration or setup. Playwright ensures consistent behaviour and API across all supported browsers, making it easier to maintain and scale your test suite. Playwright provides built-in support for device emulation using browsers like Safari and Chrome.

2. Headless and Headful Modes: Playwright allows you to run tests in headless mode (without a visible browser window) or headful mode (with a visible browser window). Headless mode is useful for running tests in CI/CD pipelines. Headful mode is beneficial for debugging, visual inspection, or when you need to interact with the browser during test execution.

3. Automatic Waiting: Playwright automatically waits for elements to be ready before interacting with them, reducing the risk of test flakiness caused by timing issues. It employs intelligent waiting strategies, such as waiting for network requests to complete or DOM mutations to occur, ensuring that tests are executed reliably and consistently.

4. Network Interception: Playwright provides powerful network interception capabilities, allowing you to intercept and modify network requests and responses during test execution. This feature is useful for testing scenarios involving APIs, mocking responses, simulating network conditions, or bypassing authentication mechanisms.

5. Multiple Contexts: Playwright allows you to create multiple browser contexts within a single test run, effectively simulating different user sessions or environments. This feature is particularly useful for testing scenarios involving multi-user interactions, such as chat applications or collaborative tools.

6. Powerful Selectors: Playwright offers a rich set of selector strategies, including CSS selectors, XPath, text selectors, and more. It also provides advanced selector options, such as handling dynamic elements, selecting elements based on their visibility or accessibility, and selecting elements within iframes and shadow DOMs, which are common in modern web applications.

7. Screenshot and Video Capture: Playwright enables you to capture screenshots and record videos of your test runs with a single line of code. This feature is invaluable for debugging, visual regression testing, and generating visual artifacts for documentation or reporting purposes.

8. Isolation and Parallelism: Playwright provides built-in support for running tests in isolation and in parallel. Test isolation ensures that each test run is independent and doesn’t interfere with other tests, preventing state pollution and improving test reliability. Parallel test execution can significantly speed up your test suite by utilizing multiple CPU cores or machines, reducing overall test execution time.

Playwright Test Automation Framework

Playwright’s architecture is designed to provide a robust, flexible, and high-performance framework for browser automation. Its support for multiple browser engines, isolated browser contexts, and powerful API makes it an excellent choice for web scraping, automated testing, and other browser automation tasks. The architecture ensures that tests and scripts are reliable, efficient, and easy to maintain.

Key Components and Processes

  1. Client Side (Automation Scripts):
    • Languages Supported: Playwright supports JavaScript and TypeScript “natively”, while also providing “bindings” for Java, Python, and C#  for writing automation scripts.
    • Test Script Creation: Users write test scripts in their preferred language. These scripts include test cases, interaction commands, and assertions. JSON is often used for configuration and data exchange.
  1. WebSocket Connection:
  • Handshake: When a test script is executed, it initiates a connection to the Playwright server (Node.js). This connection involves an initial handshake to establish communication.
  • Full Duplex (Bi-Directional) Communication: Once connected, there is a bi-directional communication channel between the client and the server. This is essential for sending commands to the browser and receiving responses or events in real time.
  • Open and Persistent Connection: The WebSocket connection remains open and persistent throughout the session, allowing continuous interaction between the test scripts and the browser.
  • Connection Closure: After test execution, the connection can be closed either by the client or the server, marking the end of the session.
  1. Server Side (Node.js):
  • Node.js Server: The server side is managed by a Node.js application, which orchestrates the interaction between the client scripts and the browsers.
  • Handling Commands and Events: The Node.js server receives commands from the client, processes them, and sends appropriate instructions to the browsers. It also listens for events from the browser and relays them back to the client.
  1. Browser Automation (CDP and CDP+):
  • CDP (Chrome DevTools Protocol): Playwright utilizes the CDP for interacting with Chromium-based browsers. CDP manages the render, browser, and network processes, which are essential for rendering pages, managing browser sessions, and handling network interactions.
  • CDP+: The image also mentions CDP+ for browsers like Firefox and WebKit (Safari). Playwright extends support to these browsers by using protocols similar to CDP, ensuring a consistent API across different browsers. Each browser process (render, browser, network) is managed to simulate user interactions accurately.

How Playwright Test Execution Works:

  1. The client (test script) sends instructions to the server over the WebSocket connection.
  2. The server receives these instructions and translates them into commands that can be understood by the browser instances.
  3. The server communicates with the browser instances using either CDP or CDP+, depending on the requirements.
  4. The browser instances execute the commands, such as navigating to web pages, interacting with elements, or capturing screenshots.
  5. The results or data from the browser instances are sent back to the server.
  6. The server relays the results or data back to the client over the WebSocket connection.

Also Read: Playwright vs Cypress: Head-to-Head Comparison

Playwright Automation Tutorial (Step-by-Step)

Learn how to automate web testing using Playwright in JavaScript, TypeScript, or Python with real-world examples. Includes code snippets, project folder structure, and cloud execution guides.

Below are the steps for performing Playwright installation on a Windows machine:

Step 1: Installation of Node.js

Playwright is based on Node.js, so we need Node.js installed in our system. We can do this using the official website and download the latest version (https://nodejs.org/), after installing it be can validate the installation status using a command on the terminal.

node -v
npm -v
// These commands will display the installed Node.js and npm versions

Step 2: Create a New Node.js Project:

In this step, we will be creating a new directory for the playwright project and navigating to it using the terminal.

mkdir my-playwright-project
cd my-playwright-project
npm init -y

The above commands will create a new Node.js project with a `package.json` file.

For a step-by-step walkthrough, check out our dedicated Playwright Installation Guide.

Folder structure of the Playwright automation tool

The screenshots below demonstrate how Playwright creates a default folder hierarchy when it first launches. Below is a detailed description of each of these files and folders that the Playwright framework has.

image8

The image shows the folder structure of a Playwright automation tool project. Here’s an explanation of each item in the structure:

  1. .github: This directory typically contains GitHub-specific files and configurations, such as GitHub Actions workflows.
  2. node_modules: This directory contains all the Node.js modules installed for the project. These are the dependencies specified in package.json.
  3. tests: This directory likely contains the Playwright test files. These files define the tests that will be executed using Playwright. We normally create a new test file in this folder.
  4. tests-examples: This directory contains example test files or templates that can be used as references when writing new tests.
  5. .gitignore: This file specifies which files and directories should be ignored by Git. Commonly ignored files include node_modules, logs, and build directories.
  6. package-lock.json: This file is automatically generated and includes the exact versions of installed dependencies. It ensures that the project is consistently installed across different environments.
  7. package.json: This file contains metadata about the project, including its dependencies, scripts, and other configurations. It is crucial to manage the project with Node.js.
  8. playwright.config.js: This configuration file is specific to Playwright. It defines settings and options for running Playwright tests, such as the browser settings, test directory, timeout configurations, etc.

Playwright Folder Structure Best Practices

Organizing your Playwright project efficiently is key to scalable and maintainable automation.

Below are best practices for structuring your tests and configuration files:

  1. Keep test scripts in a dedicated tests folder.
  2. Use a separate tests-examples folder for sample scripts.
  3. Maintain a playwright.config.js or .ts file at the root for all configuration settings.
  4. Include .gitignore unnecessary files node_modules and logs.
  5. Group-related tests using subfolders tests for better clarity.
  6. Optional: Add a utils or helpers folder for reusable functions.

Creating Your First Script in Playwright with a Detailed Example

Before creating the first script, we need to understand a few concepts in Playwright.

async and await

async and await are used to work with asynchronous code in JavaScript. They are essential when dealing with operations that take time to complete, such as network requests or file operations.

  • async: This keyword is used to define an asynchronous function.
  • await: This keyword is used to wait for a Promise to resolve before continuing execution.

Example:

test()

In Playwright’s test runner (@playwright/test), a test is used to define individual test cases.

Example:

This example defines a basic test that navigates to a page and checks if the title is “Example Domain”.

describe() 

Describe is used to group related tests together. This helps in organizing tests better, especially when you have a large number of tests.

Hooks 

Hooks are functions that are executed at specific points in the test lifecycle. Common hooks include beforeAll, afterAll, beforeEach, and afterEach.

Assertions 

Assertions are used to verify that the application behaves as expected. Playwright uses except for assertions. The expect function takes an actual value and provides various matcher methods to assert against the expected value.

Automate Your First Playwright Test Case

Let’s create a .spec file ‘testGrid.spec.js’ under the folder tests.

We are covering the scenario where the user can log in, navigate to the codeless automation section, verify the navigation to a new tab by clicking on the link  ‘Real Device Cloud’, return to the parent page, and log out successfully

Let’s take Playwright  testing examples to test end-to-end test scenarios from login to the site https://testgrid.io/ with valid credentials, navigate to the codeless automation section, verify the navigation to a new tab by clicking on the link  ‘Real Device Cloud’, return to the parent page, and log out successfully

Test Scenario

  1. Visit the Site https://testgrid.io/
  2. Log in to the site with valid credentials 
  3. Verify user is logged in by varying the text  “Dashboard.”
  4. Click on the ‘Codeless’  link under the Automation section
  5. Verify the text “Let’s get you started with codeless automation.”
  6. Open The Link ‘Real Device Cloud‘ in a New Tab and then Back To the Parent Page
  7. Verify text “Selenium” to make sure the user is back to the parent page
  8. Log out of the application

Write a simple Playwright  test in the file ‘testGrid.spec.js’ which covers the following functionality for the website https://testgrid.io/

Code walkthrough

To understand the Playwright testing example script in detail. Let’s undertake the above code walkthrough.

Imports the necessary Playwright modules for browser automation, testing, and assertions.

Defines a test named “Testgrid.io Scenario” that uses a browser instance.

Define a Test Scenario:

  • Set up Browser Context and Page: Creates a new browser context and a new page within that context.
  • Navigate to Testgrid.io: Opens the Testgrid.io website.
  • Log in to the Site: Fills in the login form with email and password, clicks the sign-in button, and waits for 7 seconds.
  • Verify Successful Login: Checks if the “Dashboard” text is visible, indicating a successful login.
  • Navigate to Codeless Automation: Click on the “Codeless” link under the Automation section.
  • Verify Codeless Automation Page: Verifies the presence of the text related to codeless automation and clicks the back button.
  • Open Real Device Cloud in New Tab: Opens the “Real Device Cloud” link in a new tab, waits for the new page to load, closes the new page, and returns to the original page.
  • Verify Return to Parent Page: Checks if the “Selenium” text is visible to confirm the user is back on the parent page.
  • Logout from the Application: Clicks on the dropdown menu, selects “Logout”, and closes the browser context.

Execute The Test Cases Locally

To execute the test cases, you can use Playwright commands in your terminal. Playwright supports both headed mode (where you can see the browser window) and headless mode (where tests run in the background without a visible browser window). 

In the section below, you will see how we can run Playwright test automation in headed and headless mode.

Run Test Cases In Headed Mode:

In the headless mode, you can see that test cases are executed in the visible browser window.

  • Open your terminal.
  • Navigate to the directory where your Playwright tests are located.
  • Run the command to execute the tests in headless mode.

Run the command npx playwright test –ui or yarn playwright test –ui. As we run the command, it will open a screen below. Click on the .spec file ‘testGrid.spec.js’ to run the test case in headless mode.

playwright Run Test Cases In Headed Mode:

When we click on testGrid.spec.js, the test case starts executing, and finally, the test case passes successfully. 

Below are the screenshots of the test case execution locally

image6 2
image5 4

In the final step user logs out of the application

playwright testing tutorial

Run Test case in Headless Mode

By default, Playwright runs in “headless mode,” where the browser runs in the background without opening a visible browser window.

Command to run the test case in headless mode: npx playwright test or yarn playwright test

Run the command: 

‘npx playwright test tests/testGrid.spec.js’. As you execute this command, the test case starts executing in headless mode. 

In the screenshot below, you can see the test case start executing in headless mode in Chrome browser. Once execution is completed, the test cases passed in Chrome 

playwright Run Test case In Headless Mode

Run the command  ‘npx playwright show-report’ Below the attached HTML report 

playwright test

Automate Playwright Test Case In the Cloud

Before diving deep into how to run Playwright test cases in the cloud, the following requirements should be met

Pre-Execution Steps

Install Node.js

  • Node.js (version 14 or later). Confirm by running:
    node -v

npm -v

Install Playwright

  • Install the Playwright test framework if it’s not already set up.
  • Run the following commands in your terminal:

npm install -D @playwright/test

npx playwright install

Set Up a TestGrid Account

  • Sign up or log in to your TestGrid account at testgrid.io.
  • Obtain the following credentials from your TestGrid dashboard:
    • User Token: Your unique authentication token.
    • SELENIUM_REMOTE_URL: The URL for TestGrid’s remote browser execution.
    • Device ID (UDID): The unique identifier for the device or browser you’ll use for testing.

Set Up and Execute Test Case In the Cloud

Before you can execute your Playwright test cases on TestGrid’s cloud infrastructure, a proper setup is essential to ensure seamless remote testing. Below are the key steps to prepare your environment and configure the necessary components.

Step 1: Access the Playwright Section

  • Log in to your TestGrid account.
  • From the sidebar, select the Playwright option. Here, you’ll find device selections, setup details, and the command for remote test execution.

Step 2: Set Up Your Test Project

You can either build a new Playwright project or use a sample project from the TestGrid dashboard.

set up project for execute playwright test
  • Download the sample project and navigate to its directory in your terminal:
    cd ~/Downloads/sample_playwright_project, Or Create your own folder, install Playwright and create a test case under this folder.
  • Verify that the directory includes a valid playwright.config.ts or playwright.config.js file.
  • In our case, we are creating our own project by installing Playwright and creating the test cases inside it.

We are using the scenario below to automate and execute the same test case in the cloud.

Test Case 1: 

  • Searches for the TestGrid website on DuckDuckGo.
  • Click the search result titled: “AI-powered End-to-End Testing Platform – TestGrid”.
  • Navigates to the Sign In page.
  • Enter credentials:
    • Email: demo@demo.com
    • Password: demo
  • Click the Sign In button to attempt login.

Test Case 2: 

  • Searches for the DemoQA website on DuckDuckGo.
  • Click on the “DEMOQA” link from the search results.
  • Navigates to the “Elements” section.
  • Clicks on the “Check Box” item.
  • Interacts with a specific node in the checkbox tree structure.

Code snippet:

Step 3: Run Tests Remotely

Copy the remote execution command from the TestGrid dashboard and run it in your terminal within the project directory. 

execute playwright test in minutes with testgrid

Here’s an example:

SELENIUM_REMOTE_URL=http://{your_domain}.testgrid.io/browserrun{port} \

SELENIUM_REMOTE_CAPABILITIES='{

  “browserName”: “chrome”,

  “tg:udid”: “101”,

  “tg:userToken”: “{User_token}”

}’ \

npx playwright test –headed

Replace {your_domain}, {port}, and {User_token} with your specific TestGrid credentials.

As soon as we trigger the above test command from the terminal, the test case starts executing on the local machine and the TestGrid cloud environment.

Step 4: Check Your Results

After running the above command, we can see the report in two convenient ways:

Locally: See execution logs in your terminal and access a generated HTML report.

output of generated HTML report
HTML report

Test Case Execution TestGrid

Once the execution starts, you will see the browser ‘chrome’ is connected, and the test case starts execution.

playwright testing selecting devices in testgrid

Below are some of the screenshots of the TestGrid cloud, where you can see the test case mentioned above executing.

image2 min
duckduckgo
image12 min
image4 min

Dashboard:  

To view the report in the Test Grid dashboard, follow the Path  Automations –> Select Browser Chrome-101. You will see the screen below

 

playwright testing demo

Click on the first executed session from the screenshot below, and you will see the test case that we executed displayed with VIDEO

playwright testing step in testgrid
playwright testing steps

Playwright Best Practices 

Below are a few best practices of Playwright. By following these best practices, you can streamline your testing process, enhance reliability, and maintain code readability:

Leverage Playwright’s Assertions:

Playwright provides built-in assertions like toBeVisible, toHaveText, and toHaveURL to validate the application state after user interactions. This simplifies test logic and improves maintainability.

Leverage Playwright’s Wait Strategies:

Playwright offers functionalities like waitForSelector, waitForNavigation, and expect with timeouts to ensure elements are loaded and ready before interaction. This improves test reliability.

Example:

Use await page.waitForSelector(‘#submit-button’) before clicking the submit button.

Keep Tests Independent:

Each test should function independently, with its own data, cookies, and local storage. This makes tests more reliable and easier to debug. Playwright offers hooks like beforeEach and afterEach to set up and tear down test environments.

Take Advantage of Playwright’s Tooling:

Playwright offers tools like Playwright Inspector for debugging tests visually, Trace Viewer for analyzing test failures, and Codegen for generating test code from recorded browser actions.

Use chaining and filtering

Locators can be combined to focus the search on a specific section of the page.

You can also use filter locators by text or by another locator.

Conclusion 

Playwright offers a powerful and versatile framework for test automation, making it a valuable tool for developers and testers alike. Its ability to handle multiple browsers, provide cross-platform support, and offer rich APIs for interaction and validation makes it stand out in the test automation landscape. By following the step-by-step guide, users can leverage Playwright’s capabilities to create reliable, efficient, and scalable automated tests, ultimately enhancing the quality and performance of their applications. Embracing Playwright can streamline testing processes, reduce manual effort, and ensure a more robust and seamless user experience.