What Is Playwright: A Tutorial on How to Use Playwright

Explore Playwright with this tutorial! Learn how to set up and use Playwright for seamless automated testing with practical examples.

Chapters

Total Chapters (22)

Chapter 1 : What is Playwright

Triangle

Overview

Playwright is an open-source automation framework that is used for testing web applications. It allows you to automate browser interactions and provides a robust, reliable, and fast way to test modern web applications across different browsers, including Chromium (Chrome, Edge), Firefox, and WebKit (Safari).

What Is Playwright?

Built by Microsoft, Playwright is a Node.js library that, with a single API, automates websites and web apps running on Chromium, Firefox, and WebKit. These APIs can be used by developers writing JavaScript code to create new browser pages, navigate to URLs, and then interact with elements on a page. In addition, since Microsoft Edge is built on the open-source Chromium web platform, Playwright can also automate Microsoft Edge.

Playwright launches a headless browser by default. The command line is the only way to use a headless browser, as it does not display a UI. Playwright also supports running full (non-headless) Microsoft Edge.

When writing this tutorial, Playwright has 65.6k Stars and 3.6k Forks on GitHub .

Why Use Playwright for Web Automation?

Playwright stands out due to its cross-browser, cross-platform, and cross-language capabilities.

Here’s why it’s a popular choice:

  • Broad Compatibility: Playwright works with all major browsers (Chromium, WebKit, Firefox) on Windows, Linux, and macOS and supports multiple programming languages like Java, JavaScript, Python, and .NET, offering a unified API for automation.
  • Resilient and Flaky-Test Resistant: Playwright’s auto-wait feature automatically waits for elements to become actionable, reducing flakiness. Its web-first assertions and retry logic help ensure tests are reliable without needing manual timeouts.
  • Complete Test Isolation: Each test runs in a separate browser context, simulating a brand new browser profile, which ensures no interference between tests. You can save authentication states, avoiding repeated logins while keeping tests independent.
  • Advanced Testing Scenarios: Playwright allows testing of complex workflows involving multiple tabs, users, or contexts and can interact with shadow DOM elements and dynamic content using real browser inputs, mimicking genuine user actions.
  • Robust Debugging and Tools: With features like the Playwright Inspector, Codegen, and Trace Viewer, you can easily create, inspect, and debug tests. These tools provide comprehensive insights into test execution, complete with videos, screenshots, and DOM snapshots.
Note

Note : Test your mobile web apps with Playwright. Try LambdaTest Now!

Playwright Architecture

To understand how Playwright's architecture works, we will compare its work with that of Selenium. Selenium sends each command as an independent HTTP request and receives JSON responses. Each interaction, such as opening a browser window, clicking an element, or entering text into an input box, is then sent as a separate HTTP request.

This means we have to wait longer for responses and increases the chances of errors.

WebSocket connection

Instead of communicating with each driver through a separate WebSocket connection, Playwright relies on a single WebSocket connection to communicate with all drivers, which remains in place until testing is finished. This allows commands to be sent quickly on a single connection, thus reducing the points of failure.

How to Get Started With Playwright?

With the basics covered, it’s now time to start implementing web automation with Playwright. Playwright supports multiple programming languages such as Java, JavaScript, TypeScript, Python, and .NET.

In this tutorial, we will be using the TypeScript API of Playwright to set up and run our tests.

Installing Playwright

There are two ways to install Playwright :

  • Using the Node.js package manager like npm.
  • Using the Playwright VS Code extension.
  • Navigate to the extension manager on VS Code and search for Playwright. Then, install the official Playwright Test for VS Code, as shown in the image below:
  • Playwright Test for VS Code
  • Once the official extension is installed, use the Install Playwright action from the command panel to get started.
  • compatible with Playwright version

    All the test scenarios used for the demo are compatible with Playwright version 1.45.3, Node.js version 20.16.0, and npm version 10.8.2. The installation comes with a working set of tests, which are available under the tests folder.

Running Your First Test

Let us now write our first test case using Playwright TypeScript. For this, we will be using LambdaTest eCommerce Playground, and the test will be run on our local machine.

For more such tutorials, subscribe to the LambdaTest YouTube Channel .

Test Scenario 1:

  • Verify if the title of the LambdaTest eCommerce Playground website has the string ‘Your Store’

Implementation:

import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/');
  await expect(page).toHaveTitle('Your Store');
});

Code Walkthrough:

The test script navigates to the LambdaTest Demo eCommerce Playground website using the page.goto() method. It verifies that the page's title matches the text Your Store using the expect() assertion with the toHaveTitle() method.

Test Scenario 2:

  • Verify if the Shop by Category button exists and has the aria-expanded attribute set to false.

Implementation:

test('shop by category button has aria-expanded false', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/');
  await expect(page.getByRole('button', { name: 'Shop by Category' })).toHaveAttribute('aria-expanded', 'false');


});

Code Walkthrough:

The test script navigates to the LambdaTest eCommerce Playground website using the page.goto() method. It then uses the page.getByRole() locator to locate the button identified by the text content Shop by Category. Finally, it uses the expect() assertion with the toHaveAttribute() method to check that the button has an aria-expanded attribute with a value of false.

Test Scenario 3:

  • Verify if the text ‘This is a dummy website for Web Automation Testing’ is visible on the LambdaTest eCommerce Playground website homepage.

Implementation:

test('dummy website text matches', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/');
  await expect(page.getByText('This is a dummy website for Web Automation Testing')).toBeVisible();
});

Code Walkthrough:

The test script navigates to the LambdaTest eCommerce Playground website using the page.goto() method. It then uses the page.getByText() locator to find the text This is a dummy website for Web Automation Testing. Finally, it calls expect().toBeVisible() method to ensure that the text is visible on the page.

Test Scenario 4:

  • Verify if the banner on the homepage has an alt text ‘Iphone 11 pro max’.

Implementation:

test('alt text for banner image exists', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/');
   await page.locator('#mz-carousel-217925').getByRole('listitem').nth(1).click();
  await expect(page.getByAltText('Iphone 11 pro max')).toBeVisible();
});

Code Walkthrough:

The test script begins by inspecting the banner image on the homepage using Chrome DevTools to confirm that it has an alt text. It then locates the images within a carousel using the page.locator(#mz-carousel-217925) and applies Playwright locator chaining to select the first child in the carousel with the getByRole('listitem') locator.

The script then uses the getByAltText('Iphone 11 pro max') locator to find the banner image. Finally, it uses the expect() assertion to ensure that the banner image element is visible on the page.

Test Scenario 5:

  • Verify if the placeholders for Email and Password exist on the My account page.

Implementation:

test('email and password placeholders exist and are editable', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/login');
  await expect(page.getByPlaceholder('E-Mail Address')).toBeEditable();
  await expect(page.getByPlaceholder('Password')).toBeEditable();
});

Code Walkthrough:

The test script inspects the My Account page to confirm that placeholders are available for the email and password fields. It then uses page.getByPlaceholder() to locate the E-Mail Address input field and calls expect().toBeEditable() to ensure it is editable.

Similarly, it uses page.getByPlaceholder() to locate the Password input field and calls expect().toBeEditable() to verify that it is also editable.

Test Execution:

To execute the tests, run the below command:

npx playwright test

The screenshot below shows the test execution report using the npx playwright show-report command:

However, to ensure our web application performs reliably across various operating systems like macOS and Windows, as well as different browsers such as Firefox and Safari, it's essential to test it across all these setup combinations.

Building such an infrastructure is neither practical nor cost-effective. The solution is to use cloud grids like LambdaTest. It is an AI-powered test execution platform that allows you to run Playwright automation across various web browsers online.

...

Web Automation With Playwright Using LambdaTest

The above test scenarios have been run on the local grid. To run the same Playwright tests on the LambdaTest platform, we need to make additional configurations in our local setup.

Implementation:

We start first by creating a .env file in our project and setting up our connection to LambdaTest using the Username and Access Key, which can be obtained from your LambdaTest Account Settings > Password & Security.

Next, we modify the playwright.config.ts file to support running the tests locally or on the LambdaTest Playwright grid.

import { defineConfig, devices } from '@playwright/test';


export default defineConfig({
  timeout: 5 * 60 * 1000,
  testDir: './tests',
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    // baseURL: 'http://127.0.0.1:3000',


    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
  },


  /* Configure projects for major browsers */
  /* Configure projects for major browsers */
  projects: [
    {
      name: "chrome:latest:Windows 11@lambdatest",    
    },


    /* Comment the above names object & Uncomment the below name object to run on local */
    // {
    //   name: 'chromium',
    //   use: { ...devices['Desktop Chrome'] },
    // },  
  ],


});
LambdaTest

In the projects array, we add a new name object to support running tests either locally or on the cloud. This object is used later in the lambdatest-setup.ts file to determine the running environment.

Capabilities can be generated using the LambdaTest Automation Capabilities Generator as per the test setup we require. We’ve also added a timeout: 5 * 60 * 1000 to ensure we allow enough time for the connectivity setup to the LambdaTest grid and tests to run.

Next, we add another lambdatest-setup.ts file, which holds the code to configure the LambdaTest Playwright grid.

// LambdaTest capabilities
const capabilities = {
  browserName: "Chrome", // Browsers allowed: 'Chrome', 'MicrosoftEdge', 'pw-chromium', 'pw-firefox' and 'pw-webkit'
  browserVersion: "latest",
  "LT:Options": {
    platform: "Windows 11",
    build: "Playwright Demo",
    name: "Playwright Demo",
    user: process.env.LT_USERNAME,
    accessKey: process.env.LT_ACCESS_KEY,    
    network: false,
    video: false,
    console: false    
  },
};

In this file, we configure LambdaTest to use Windows 11 and the latest version of Chrome in the capabilities object. We also modify the base test method of Playwright to run tests on the cloud grid or locally based on the configuration done in playwright.config.ts projects array.

We then modify our test file to import our custom test method configured in the lambdatest-setup.ts file.

import { expect } from '@playwright/test';
import test from "../lambdatest-setup";

Test Execution:

Now execute the tests using the below command:

npx playwright test

The LambdaTest Web Automation Dashboard will immediately start reflecting the running tests build.

Web Automation Dashboard

On clicking the build, you will be presented with a granular view of each test including the step-by-step test execution. Video, console, and network logs will also be shown if these features are enabled in the capabilities object in the lambdatest-setup.ts file.

step-by-step test execution

In the playwright.config.ts file, if we change the projects array to leverage macOS and run the tests again, LambdaTest will run the tests on the specified version of macOS.

  projects: [
    {
      name: "Chrome:latest:macOs Sonoma@lambdatest",    
    },


    /* Comment the above name object & Uncomment the below name object to run on local */
    // {
    //   name: 'chromium',
    //   use: { ...devices['Desktop Chrome'] },
    // },  
  ],

Now rerun the tests with the same test execution command (npx playwright test). You can notice the updated infrastructure using macOS and the latest version of Chrome for test execution.

latest version of Chrome

Learning Resources for Playwright

You can explore the Playwright resources listed below to deepen your understanding and enhance your learning journey. These resources provide valuable insights, tutorials, and best practices that will help you gain a more comprehensive knowledge of the subject.

Articles

Videos

Certifications

In addition to the above learning resources, it’s essential to elevate your Playwright skills further.

Following are the LambdaTest Certifications in Playwright that provide a great opportunity to validate and showcase your expertise, taking your knowledge to the next level.

Frequently asked questions

  • General →
  • LambdaTest related FAQs
What is Playwright testing?
Playwright is a Node.js library that lets you script and automates browsers using the same API, like Chrome, Firefox, and Safari. This cross-browser automation is evergreen, capable, reliable, and fast! It also lets you access the REST API of your application to help you perform API testing.
Is Playwright better than Selenium?
The Playwright performs various actionability checks on elements before performing specific actions, thereby making the execution of the tests more stable. In Selenium, we use implicit and explicit waits. The scripts are written in Playwright execute faster than those written in Selenium.
Can we use Playwright for API testing?
Yes! You can use Playwright for API testing.
What browser and OS versions does Playwright on Automate support?
LambdaTest makes testing across browsers a breeze. Run Playwright tests in parallel (across 50+ browsers and OS configurations) to cut down on test execution time further. Not only this, reduce feedback time and get your product out faster with LambdaTest.
How do I start a Playwright test?
To start a Playwright test, install Playwright, create a new file, import Playwright, and write your test using the desired browser context.
What tools does a Playwright use?
A Playwright uses automation tools like Playwright API and Playwright Test to write and execute browser automation tests, interact with web pages, and validate web app functionalities, providing efficient and reliable testing capabilities.
Does playwright need coding?
No, Playwright does not require coding. It is an end-to-end testing library that enables developers to automate actions in browsers and perform tests without extensive coding knowledge.
Is Playwright built on Selenium?
No, Playwright is not built on Selenium. It is a modern and powerful automation testing framework developed by Microsoft, offering cross-browser and cross-platform support with better performance and advanced features.
Which language is best for Playwright?
Playwright works with some of the most popular programming languages, including JavaScript, Python, Java, and C#. It also supports Chromium, Firefox, and WebKit, providing a wide range of cross-browser testing capabilities.

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud