What Is Playwright? Playwright Testing Tutorial - A Guide With Examples

Playwright is a powerful testing tool that provides reliable end-to-end testing and cross browser testing for modern web applications.

Chapters

Total Chapters (21)

Chapter 1 : What is Playwright

Triangle

What is Playwright?

Built by Microsoft, Playwright is a Node.js library that, with a single API, automates 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 end-to-end testing has slowly gained popularity. Many developers consider it one of their favorite frameworks to work with.

The State of JS survey among developers shows that while Cypress adoption is on the rise, Playwright adoption is still in the early stages of development. However, GitHub statistics show Playwright's popularity is growing (44.6k Stars and 2.2k Fork).

Playwright Statistics

Playwright launches headless browsers by default. 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.

Why use Playwright for Web Automation?

Playwright is an open-source framework developed by Microsoft and released in 2020. It is relatively new to the market but has gained popularity quickly. Microsoft continues to update and improve it based on user feedback, so if we look at the number of downloads for similar frameworks that have been on the market longer than Playwright, you can see how popular it has become. A cloud-based Playwright automation testing cloud-like LambdaTest solves the problems mentioned above.

Why Playwright

Here are a few reasons that make Playwright a must-try framework:

Releases:

The Playwright team and standard release notes also provide their release notes in the form of video walkthroughs. I haven't seen this from any of the other major frameworks, and it's a nice touch for gaining insight into how the product is developed.

Competitors:

You may be weighing the pros and cons of migrating from Selenium to Cypress, and also gaining popularity in the community.

Playwright testing stands out from its competitors because it outranks other JavaScript libraries because of its intuitive syntax and the flexibility with which it can interact with the browser across multiple pages and domains. Lastly, the execution speed of test scripts on Playwright tops other automation frameworks. The ChecklyHQ team created this benchmark report after performing in-depth execution speed monitoring of the major automation tools.

Integrations:

Playwright comes with native integration. For example, the Playwright has Docker images, allowing you to run tests quickly in an isolated and controlled environment. Native integrations are available for the best CI/CD tools, including GitHub Actions, Azure Pipelines, CircleCI, Jenkins, and GitLab. They also support your existing JavaScript test runners, like Jest/Jasmine, AVA, and Mocha, which is helpful if you are porting from an existing code base.

Lastly, Playwright has direct integration with Selenium grid online. This is essential for running larger suites of tests at scale and managing parallel execution through Selenium Grid.

Note

Note : Run your Playwright test scripts instantly on 50+ browser and OS combinations. Execute Playwright testing in parallel to significantly reduce test execution time. Try LambdaTest Now!

How to perform Playwright testing?

You can leverage different features offered by the Playwright framework. However, its true potential can be determined only over a cloud-based testing platform like LambdaTest. Using LambdaTest test automation cloud, you can automate Playwright tests on an online browser farm of 50+ browsers, including Chrome, Chromium, Edge, Mozilla Firefox, and Webkit.

You can also run your Playwright test scripts in parallel and trim down test execution cycles by multiple folds.

Here are some other features that make Playwright testing a breeze with LambdaTest.

  • Instant access to 3000+ real desktop and mobile environments.
  • Perform 70% faster test execution with HyperExecute - an end-to-end test orchestration cloud.
  • Mitigate test flakiness, shorten job times and get faster feedback on code changes with Test At Scale.
  • Test across multiple geographies with a geolocation testing feature.
  • 120+ third-party integrations with your favorite tool for CI/CD, Project Management, Codeless Automation, and more.

Below are the steps to run Playwright tests on the LambdaTest platform.

  • Sign up for free and login to your LambdaTest account.
  • Clone the LambdaTest LambdaTest Playwright GitHub repository
  • Install the NPM dependencies using npm install.
  • Set your LambdaTest username and access key in the environment variables. You can get them from the LambdaTest Automation Dashboard by clicking the Access Key button at the top-right.
  • Shown below is the Playwright test script that searches the term 'LambdaTest' on the Bing browser. The test is run on the Chrome browser and Windows 10 operating system.

    const { chromium } = require('playwright')
                            const { expect } = require('@playwright/test');
    
                            (async () => {
                              const capabilities = {
                                'browserName': 'Chrome', // Browsers allowed: 'Chrome', 'MicrosoftEdge', 'pw-chromium', 'pw-firefox' and 'pw-webkit'
                                'browserVersion': 'latest',
                                'LT:Options': {
                                  'platform': 'Windows 10',
                                  'build': 'Playwright Sample Build',
                                  'name': 'Playwright Sample Test',
                                  'user': process.env.LT_USERNAME,
                                  'accessKey': process.env.LT_ACCESS_KEY,
                                  'network': true,
                                  'video': true,
                                  'console': true,
                                  'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
                                  'tunnelName': '', // Optional
                                  'geoLocation': '', // country code can be fetched from https://www.lambdatest.com/capabilities-generator/
                                }
                              }
    
                              const browser = await chromium.connect({
                                wsEndpoint: 'wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}'
                              })
    
                              const page = await browser.newPage()
    
                              await page.goto('https://www.bing.com')
    
                              const element = await page.$('[aria-label="Enter your search term"]')
                              await element.click()
                              await element.type('LambdaTest')
                              await element.press('Enter')
                              const title = await page.title()
    
                              try {
                                expect(title).toEqual('LambdaTest - Search')
                                // Mark the test as completed or failed
                                await page.evaluate(_ => {}, 'lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'passed', remark: 'Title matched' } })}')
                              } catch {
                                await page.evaluate(_ => {}, 'lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: 'Title not matched' } })}')
                              }
    
                              await browser.close()
                            })()
  • Use the command: node playwright-single.js in the terminal to run the test.
  • Now, visit the LambdaTest Automation Dashboard to view your test results.

  • Playwright dashboard

You can view the details of the Playwright test session you just executed by clicking the session name. A screenshot below shows test execution details for a Playwright test, including Test Name, Test ID, selected configurations, test logs, basic information, input configuration, and test session video.


Playwright dashboard

Features of Playwright testing framework

Here are some unique features of the Playwright testing framework:

  • The framework supports cross-browser development on Chromium, WebKit, and Firefox – including Chrome, Edge, Firefox, Opera, and Safari.
  • Cross-platform execution is supported on Windows, Linux, and macOS.
  • Testing cross-language, including JavaScript, TypeScript, Python, Java, and .NET – choose the environment that suits you while still covering all areas and formats.
  • Auto-wait, smart assertions that retry until an element is found, and test data tracing – keep track of logs and videos easily.
  • Built with modern architecture and no restrictions, the application allows you to interact with multi-page, multi-tab websites like a real user and easily handles frames and browser events.
  • As the Playwright framework is aligned with the modern browser's architecture, it doesn't have the in-process test runner limitations.
  • Playwright delivers full test isolation with no overhead. It creates a browser context for each test which only takes a handful of milliseconds.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorial around Playwright, Selenium, Appium, and more.

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, then is sent as a separate HTTP request.

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

Playwright Architecture

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.

Browsers Supported by Playwright

Playwright is available in a variety of languages, and each version has different dependencies. At package install time, Playwright will either download these dependencies for you or you can use Playwright CLI to install them.

Playwright constantly updates its support of browsers, so that the latest Playwright would support the latest browsers at any time. As a result, you need to run the install command each time you update Playwright.

  • Chromium (84 & above)
  • Firefox (76 & above)
  • WebKit (13 & above)
  • Google Chrome (Chrome 66 & above)
  • Microsoft Edge (Edge 80 & above)

Playwright testing Drawbacks

Here are some Playwright testing drawbacks:

  • Playwright does not support legacy Microsoft Edge or IE11.
  • A single test() function captures screenshots, videos, and failure traces. In other words, if you have a few tests inside a test.describe() function, you will get videos and traces for each one but not for the entire root test function.
  • Playwright uses desktop browsers instead of real devices to emulate mobile devices.
  • Even though Playwright supports API testing, its APIRequest method doesn't support disabling follow redirects.
  • It doesn't support TeamCity reporter. You need to write your reporter for CI/CD builds.

Role of Playwright in Test Authoring

When working with web automation, the common challenges one faces are sluggish test execution, unreliable wait scenarios, writing a lot of boilerplate code for setting up the browser, parallel test execution, etc. With Playwright, you can overcome these challenges while making test authoring more reliable, fast, and readable.

In this section of the Playwright tutorial, let’s explore how Playwright makes test authoring fast and readable.

Playwright is simple to set up. If you pass the command npm i playwright, it will download binaries for all three supported browsers. Therefore, by passing the single command, you have the setup ready for browser automation.

Playwright works on three core concepts: browser, context, and page.

  1. Browser: To run the tests, you must initiate the browser. Using Playwright, you can use the object of the Browser class, an instance of Chromium, Firefox, or Webkit.
  2. Context: The Playwright framework achieves parallelization using browser contexts. The browser contexts are like incognito-like profiles isolated within a browser instance.
  3. Page: It is a new tab (or pop window) within a browser context. Every action on the test will be performed on the page.
  • Playwright supports three browsers: Chromium, Firefox, and Webkit. Therefore, you can write tests once and execute them across all browsers with zero or fewer configurations.
  • Playwright auto-waits for web elements before making an action. It makes the test authoring easy and avoids the additional steps of adding explicit waits.
  • It provides custom wait-for tests to wait for a selector to be available. Likewise, waiting until some specific network conditions are met is possible.
  • The Playwright prevents the need for multiple logins. It stores the session details, including cookies, within a context. Therefore, it can be used across all tests within that particular context.
  • Playwright supports resilient selectors like text content and accessibility labels to locate web elements.

The Rise of Playwright framework

While Playwright is new to the market, it already has several features that make it a strong competitor. People who want to migrate from Selenium to Playwright can do so quickly since Playwright support C#, Java, and Python. Programmers aren't limited by their language; Playwright's first release was in January 2020, and it has gained popularity ever since.

Check out The State of JS 2021 Playwright testing data on the basis of developer Satisfaction, Interest, Usage and Awareness.

Satisfaction:

Since 2020, Playwright has shown a consistent level of satisfaction among developers and testers i.e., 93% as per both 2020 and 2021 survey.

Playwright Satisfaction

Interest:

The interest in using the Playwright testing tool by developers and QA testers has also shown consistency i.e., 70% as per both 2020 and 2021 survey.

Playwright Interest

Usage:

As Playwright is comparatively new testing framework, it has shown a significant increase in its usage by developers and testers from 3% in 2020 to 10% in 2021 indicating positive growth in the coming years.

Playwright Usage

Awareness:

Playwright is a new web automation testing tool quickly gaining popularity among the developers and testers community. It showcases a rise from 19% in 2020 to 34% in 2021, indicating a positive growth in the coming years.

Playwright Awareness

Under the Experience Over Time section of the State of JS 2021 survey, it also shows:

For 2020:

Around 10.6% of developers have shown interest in using Playwright for their testing needs. The lack of awareness of the Playwright framework is at an all-time high i.e., 81.6%, but considering its still a new testing framework, it is already gaining popularity. Along with this, only 3.1% of developers would like to use Playwright again in the future.

Playwright 2020 Data

For 2021:

The percentage of developers and testers interested in using Playwright has significantly increased from 10.6% to 17%. Furthermore, considering its a new testing framework, it has shown a drastic improvement in lack of awareness, i.e., in 2020, around 81.6% of devs and testers were unaware, bringing this percentage down to around 66.3% in 2021. Along with this, the percentage of users who would like to use Playwright again has also shown a significant increase from 3.1% in 2020 to 8.9% in 2021.

Playwright 2021 Data

History of Playwright

Browser automation is not a new technology. Selenium has been around since 2004 and has been used primarily to create test suites for websites. However, programmers have also used it to take screenshots and automate tasks when websites don’t provide APIs.

However, Selenium has a reputation for being unreliable. Tests powered by Selenium are commonly flaky and often fail intermittently for non-obvious reasons that are difficult to reproduce. Due to the resource-heavy nature of Selenium as it renders entire webpages, programmers started using headless browsers instead. These browsers perform the same functions as regular browsers but don’t actually display any content. PhantomJS was one of the more popular ones.

Although headless browsers can be useful for testing simpler websites, they cannot test everything that websites can do. To test all the features of a full browser, headless browsers must emulate full browsers as closely as possible. This can be very difficult as modern browsers are so complicated.

In 2017, the landscape of browser automation changed drastically. PhantomJS, a popular framework for headless testing, was deprecated. The reason for this move was Google’s announcement of headless Chrome, which was first available in Chrome 59. Firefox followed up with a headless mode later that year. These developments led to more efficient tests and scripts and hence Playwright was born.

Playwright vs Puppeteer: A Detailed Comparison

Microsoft's Playwright by Microsoft started as a fork of Puppeteer. For those who don’t know, Puppeteer is a node library that allows the automation of Chromium-based browsers with the help of JavaScript.

Microsoft's If you look it up, the top two contributors to Puppeteer now work on Playwright. The Puppeteer team essentially moved from Google to Microsoft and became the Playwright team. As a result, Playwright is very similar to Puppeteer in many ways. Both packages use the same API methods and bundle compatible browsers by default.

The biggest differentiating point of Playwright is its cross-browser compatibility. It can drive Chromium, WebKit (the browser engine for Safari), and Firefox. Along with this, starting a new library allowed Playwright to improve ergonomics in ways that would break Puppeteer. For example, Playwright’s page.click waits for an element to be visible by default. While Puppeteer can still improve, Playwright is more useful for some situations.

The last noteworthy difference is that Playwright automation platform offers more powerful browser context features, enabling you to simulate multiple devices with a single instance. Each browser context can have multiple pages underneath it, and each context is isolated from other contexts in terms of cookies and local storage.

In contrast, Puppeteer testing makes it easy to get started with browser automation. This is in part because of its ease of use, since it controls Chrome using the nonstandard DevTools protocol and lets you intercept network requests with ease and providing additional functionality over Selenium.

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