Close announcement
Back to blog

Playwright Cheat Sheet

playwright cheat sheet

Playwright is an open-source automation library for web testing and automation. It allows developers to write scripts that can control a web browser and perform actions just like a human would, such as clicking on elements, typing text, navigating through pages, and capturing screenshots.

Playwright supports multiple browsers, including Chrome, Firefox, and WebKit, which allows for cross-browser testing. It provides a powerful API to automate web interactions and is capable of running tests in headless mode (without a browser UI) for faster execution.

Playwright cheat sheet

Playwright is often used for end-to-end testing, ensuring that web applications work as expected. It's a project maintained by Microsoft and is part of their modern testing toolset that also includes tools like Selenium and Cypress.

Let's dive into a comprehensive cheat sheet which can help you with mastering Playwright.

Why Use Playwright?

It enables interaction with elements of a web page, handling tasks from inputting text to asserting the visibility of a key element. Its robust API supports automation scenarios such as navigating browsers, managing cookies, and capturing dialog boxes.

Playwright tests can emulate complex user interactions with a web's structure, including selecting items from a list, clicking on labels, or handling CSS selectors.

Compared to tools like Cypress, Playwright offers cross-browser testing capabilities and the flexibility to write tests in multiple programming languages. Developers can write Playwright code to automate and interact with web elements, ensuring their applications work as intended in different environments. Tool also offers local parallel mode when tests are run (feature not available in Cypress).

Playwright integrates with Chrome DevTools Protocol to automate and control browser operations, providing a powerful interface for web automation and testing. This allows developers to programmatically interact with web pages, manipulate DOM elements, and monitor network requests, leveraging Chrome's extensive debugging capabilities.

Check out also our other Cheat Sheets:

Browsers

In Playwright, a Browser represents an instance of a web browser. It's not just limited to a single tab or window; rather, it's the actual program itself, like an instance of Chrome or Firefox. When you start a browser through Playwright, you're effectively opening the application which can then contain multiple web pages and contexts.

Contexts

A BrowserContext is an independent incarnation of a browser environment within Playwright. It can be thought of as an incognito session where no state is shared with other browser contexts.

This isolation is particularly useful for simulating multiple sessions or users in testing scenarios. Each context can have its own cookies, local storage, and session information, and you can have multiple contexts within the same browser instance.

Pages

A Page in Playwright is akin to a single tab or window in a web browser. It provides methods to interact with and control a single web page. Actions such as navigating to URLs, interacting with page content, and evaluating JavaScript within the context of the web page are done at this level. Pages live within a browser context, and you can have multiple pages within a single context.

Understanding Selectors and Elements

Selectors are the means by which Playwright identifies elements on a web page to interact with. They can be CSS selectors, XPath selectors, text selectors, or even custom selectors defined by the user. Once a selector is defined, Playwright can perform actions on the element it points to, such as clicking, typing, or reading text.

Elements, or more specifically ElementHandles, are objects that reference an element on a page. Once you have an ElementHandle, you can perform actions on that element, and it will ensure that the element is available and not stale. This is useful for interacting with elements that may not be immediately available due to dynamic content loading and other asynchronous behavior common in modern web applications.

The Playwright API Structure

The Playwright API is designed to be intuitive and straightforward. It mirrors the structure of a web browsing experience at a high level while providing detailed control at the lower levels. The API is organized around the following hierarchy:

  • Browser: Methods to control browser-level actions, such as launching or closing a browser.

  • BrowserContext: Methods to manage contexts, like creating new contexts or closing them, along with setting context-wide options (e.g., viewport size, geolocation, permissions).

  • Page: Methods to interact with and control a web page, like navigating to a URL, selecting elements, and executing page-level scripts.

  • ElementHandle: Methods to perform actions on individual elements, such as clicking, typing into inputs, or retrieving properties and text content.

Playwright Test Automation Cheat Sheet

Installation Guide

  1. Ensure Node.js (version 12 or above) is installed.

  2. Run npm i -D playwright to install Playwright and browser binaries.

  3. Verify the installation with npx playwright --version.

Configuring Playwright for different browsers:

  1. Install the necessary browser binaries via npx playwright install where can be chromium, firefox, or webkit.

  2. Configure the desired browser in the script by using playwright.<browserType>().

Creating your first script

  1. Install Node.js

First, ensure you have Node.js installed as Playwright is a Node library. You can download it from Node.js official website.

  1. Set Up a New Node Project

Create a new directory for your project and initialize a Node.js project:

mkdir my-playwright-project
cd my-playwright-project
npm init -y
  1. Install Playwright

Install Playwright and its dependencies:

npm i -D playwright
  1. Create a Test Script

Create a new file for your test script, for example, firstTest.js.

  1. Write Your Script

Open firstTest.js in a text editor and write your Playwright script. Here's a simple example:

const { chromium } = require('playwright');
(async () => {
   // Launch browser
   const browser = await chromium.launch();
   // Create a new page
   const page = await browser.newPage();
   // Navigate to a website
   await page.goto('https://example.com');
   // Take a screenshot
   await page.screenshot({ path: 'screenshot.png' });
   // Close browser
   await browser.close();
})();
  1. Run Your Script

Run your script using Node.js:

node firstTest.js
  1. Check the Output

After running the script, you should see a new file named screenshot.png in your project directory. This is the screenshot taken by your script.

Additional Tips:

  • Exploring Playwright Features: Playwright supports various browsers (Chromium, Firefox, and WebKit), has powerful selectors, and can handle multiple pages and contexts. Explore the Playwright documentation to learn more about these features.

  • Debugging: Use await page.pause() in your script for debugging, which allows you to inspect and interact with the page.

  • Headful Mode: Run browsers in headful mode (with a GUI) for visual debugging by passing { headless: false } to the launch method.

  • Cross-Browser Testing: You can easily test across different browsers by changing chromium to firefox or webkit.

Basic Commands

Launching browsers:

const browser = await chromium.launch({ headless: false }); // for visible browser
const page = await browser.newPage();
await page.goto('https://example.com');

Interacting with elements

Playwright can interact with HTML Input elements such as text inputs, checkboxes, radio buttons, select options, mouse clicks, type characters, keys and shortcuts as well as upload files and focus elements

Text Inputs: Using the locator.fill() method is a highly efficient technique for populating form fields. This approach automatically focuses on the targeted element and initiates an input event that inputs the specified text. It is compatible with <input>, <textarea>, and [contenteditable] elements, making it a versatile tool for form automation.

await page.getByRole('textbox').fill('Example Text');

Checkboxes and Radio Buttons: Using locator.setChecked() is the easiest way to check and uncheck a checkbox or a radio button

await page.getByLabel('Agree to Terms').check(); expect(page.getByLabel('Subscribe to Newsletter')).toBeChecked();

Select Options: The locator.selectOption() method is used to choose one or several options within a <select> element. It allows selection based on the option's value or label. This function supports the selection of multiple options simultaneously.

await page.getByLabel('Select Color').selectOption('blue');

Mouse Interactions: Perform clicks, double-clicks, right-clicks, and hovers using page.click() and page.hover().

  • Generic click
await page.getByRole('button').click();
  • Double click
await page.getByText('Item').dblclick();
  • Right click
await page.getByText('Item').click({ button: 'right' });
  • Shift + click
await page.getByText('Item').click({ modifiers: ['Shift'] });
  • Hover over element
await page.getByText('Item').hover();
  • Click the top left corner
await page.getByText('Item').click({
position: { x: 0, y: 0 }
});
  • Type Characters: Using await page.locator('#area').pressSequentially('Hello World!');, you can simulate the pressing of keys one after another. This function generates all required keyboard events, including 'keydown', 'keyup', and 'keypress' events. Additionally, you have the option to set a delay between each key press, effectively mimicking real user typing behavior.

  • Press keys one by one

await page.locator('#area').pressSequentially('Hello World!');
  • Shortcuts: For special keyboard handling, use locator.pressSequentially() and locator.press().
await page.getByText('Submit').press('Enter');
  • Upload Files: Select files for upload with locator.setInputFiles().
await page.getByLabel('Upload File').setInputFiles('path/to/file.txt');
  • Focus and Drag-and-Drop: Focus elements with locator.focus() and perform drag-and-drop with locator.dragTo().
await page.getByLabel('Input Field').focus();
await page.locator('Draggable Item').dragTo(page.locator('Drop Area'));

Advanced Interactions

  • Dealing with frames and pop-ups
const frame = page.frame({ name: 'frame-name' });
await frame.click('button#submit');
  • Uploads and downloads
await page.setInputFiles('input[type="file"]', 'path/to/file');
const [ download ] = await Promise.all([ page.waitForEvent('download'),'
page.click('a#downloadLink') ]); // waits for download to start
  • Handling network conditions and events
page.setOfflineMode(true); // To simulate offline mode await

Selectors Cheat Sheet

Common selectors and their syntax

  • CSS: page.click('button.class')

  • XPath: page.click('//button[@id="submit"]')

  • Text: page.click('text="Submit"')

Best practices for selecting elements

  • Use ID or class selectors when possible.

  • Avoid using indexes in selectors; prefer text content or specific attributes.

Custom selectors and functions

await page.$('data-testid=submit-button'); // Custom attribute selector

Working with Assertions

Overview of assertions in Playwright

  • Assertions are used to verify conditions in the browser.

  • Playwright works with assertion libraries like Chai, Jest, etc.

Common assertion examples

const title = await page.title(); 
expect(title).toBe('Expected Title');

Tips for effective assertions

  • Always wait for elements before asserting.

  • Use assertions to verify the state of the application, not just the presence of elements.

Automation Recipes

Login automation example:

await page.type('input[name="username"]', 'user');
await page.type('input[name="password"]', 'pass');
await page.click('text="Log in"');

Data scraping example

const data = await page.evaluate(() => {
// Return scraped data from page
return document.querySelector('.elementClass').textContent
});

End-to-end test scenario

E-Commerce Checkout Process Automation

1. Environment Setup

Initialize Playwright: Set up the Playwright environment with the required browser (e.g., Chromium).

Test Data Preparation: Prepare test data, like product details and user credentials.

2. Launch Browser and Navigate to E-Commerce Site

Start Browser: Launch the browser in headless or non-headless mode based on the requirement.

Open Website: Navigate to the e-commerce website's homepage.

3. User Login

Access Login Page: Click on the login link/button.

Enter Credentials: Fill in the username and password fields.

Submit Form: Click on the submit button.

Verify Login: Check if the user's account page is loaded.

4. Product Selection

Browse Products: Navigate to the product category.

Select a Product: Click on a product.

Add to Cart: Click the 'Add to Cart' button.

Verify Cart: Ensure that the product is added to the cart.

5. Cart Review

View Cart: Navigate to the shopping cart.

Check Product Details: Verify the selected product's details (name, quantity, price).

Proceed to Checkout: Click on the 'Proceed to Checkout' button.

6. Checkout Process

Delivery Information: Fill in the delivery address and contact information.

Choose Delivery Option: Select a delivery method.

Payment Information: Enter payment details (credit card, PayPal, etc.).

Review Order: Confirm all details are correct.

7. Place Order

Submit Order: Click the 'Place Order' button.

Verify Order Confirmation: Check for a successful order confirmation message or page.

Order Details: Optionally, capture order details like order number for further verification.

8. Logout and Close Browser

Logout: Click the logout button.

Close Browser: Close the browser session.

Additional Considerations:

  • Assertions: Throughout the test, include assertions to verify if each step is completed as expected (e.g., page titles, confirmation messages).

  • Error Handling: Implement error handling for scenarios like out-of-stock products or payment failures.

  • Responsive Design Testing: Optionally, test the checkout process on different screen sizes.

  • Cross-Browser Testing: Run the test across different browsers supported by Playwright.

  • Clean Up: Ensure that the test cleans up any data it creates, like removing test orders from the system.

Debugging Playwright Scripts

Tools and techniques for debugging

  • Use page.on('console', message => console.log(message.text())); to listen to page console events.

  • Use DEBUG=pw:api before running the script to get Playwright's API call logs.

Common errors and their solutions

  • Element not found: Ensure the selector is correct and the element is loaded.

  • Timeout: Increase timeout or use page.waitForSelector().

Logging and reporting

  • Use built-in page.screenshot() and page.video() for visual logs.

Integration with Test Runners

Integration with Test Runners

  • Compatibility with Popular Test Runners: Playwright is designed to work with a range of test runners like Jest, Mocha, and others. This flexibility allows developers to choose their preferred testing environment.

  • Seamless Integration: Playwright integrates smoothly with these test runners, enabling features like parallel test execution, test retries, and reporting.

  • Automated Browser Testing: Playwright can automate tests in multiple browsers (like Chrome, Firefox, and Safari), ensuring cross-browser compatibility.

  • CI/CD Integration: Playwright's compatibility with test runners makes it easy to integrate automated browser tests into Continuous Integration/Continuous Deployment (CI/CD) pipelines.

Organizing Tests and Suites

  • Using describe Blocks: Tests in Playwright can be grouped using describe blocks. This is a common practice in test runners like Jest and Mocha. describe blocks help in organizing tests into logical groups or suites, making it easier to understand the structure of tests.

  • Individual Tests with test or it: For writing individual tests, Playwright uses the test or it functions. These functions define individual test cases. test is generally used in Jest, while it is common in Mocha. Both serve the same purpose of delineating a single test.

  • Hierarchical Test Organization: By combining describe blocks with test or it, tests can be organized hierarchically. This hierarchy aids in creating structured, readable, and maintainable test suites.

  • Scoped Setup and Teardown: Within these blocks, Playwright allows for scoped setup and teardown (using hooks like beforeEach, afterEach), which is essential for setting up the conditions for each test and cleaning up afterward.

  • Tagging and Filtering: Tests can be tagged, and these tags can be used to filter tests during execution. This is particularly useful in large test suites where you might want to run only a subset of tests based on certain criteria.

Parallel execution and headless mode

Parallel Execution:

Parallel execution in Playwright refers to the ability to run multiple browser instances or tests simultaneously. This is crucial for speeding up the testing process, especially when dealing with a large suite of tests.

Playwright supports parallel execution. It can also integrate with Jest or Mocha testing frameworks.

In Playwright, each test or browser instance runs in its own context, which ensures that tests do not interfere with each other, providing isolation and more reliable results.

Headless Mode:

Headless mode in Playwright allows you to run browsers without a graphical user interface. This is especially useful for automated testing, particularly in continuous integration (CI) environments where you may not need a display for running tests.

Running in headless mode often results in faster execution of tests because it doesn't need to render the UI elements on the screen.

You can enable headless mode in Playwright by setting the headless option to true when launching a browser. For example, in Playwright for JavaScript, you would use browserType.launch({ headless: true });.

Continuous Integration and Deployment

Setting up Playwright in CI/CD pipelines:

  • Use the playwright-github-action for GitHub Actions integration.

  • Configure environment variables for sensitive data like login credentials.

Docker integration:

  • Use Playwright's official Docker image to run tests in containers.

Best practices for CI/CD with Playwright:

  • Cache browser binaries between runs.

  • Use artifacts for storing screenshots and videos from test runs.

Resources

Official documentation: Playwright Documentation

Community forums and support: Playwright GitHub Discussions

Happy (automated) testing!

FAQ

What is Playwright Cheat Sheet?

A: The Playwright Cheat Sheet is a resource that provides a quick reference guide for leveraging Playwright for browser automation and testing.

How can I explore the capabilities of Playwright?

A: To explore the features and capabilities of Playwright, you can refer to the official documentation and tutorials provided by the Playwright team.

What are the key features of Playwright?

A: Playwright offers features such as cross-browser testing, parallel and headless execution, and the ability to automate tasks across different web platforms.

A: It is recommended to set up Playwright for automation by following the installation and setup instructions provided in the official Playwright documentation.

How can I locate a specific element on a web page using Playwright?

A: You can use the Playwright API to locate elements on a web page by using methods such as 'locate', 'match', and 'explicit selection'.

Can Playwright be used for mobile automation?

A: Yes, Playwright provides support for mobile automation, allowing you to automate tasks and tests on mobile platforms.

What are the benefits of migrating to Playwright from other automation frameworks like Cypress?

A: Migrating to Playwright from frameworks like Cypress can offer benefits like local parallel testing. Playwright is also much easier when it comes to complexity of the code - and it also supports multiple languages.

How can I ensure accessibility in automated tests using Playwright?

A: You can ensure accessibility in automated tests using Playwright by leveraging features such as 'text alternative', 'accessible value await', 'label await', and 'placeholder'.

Can Playwright be integrated with Git for version control?

A: Yes, Playwright can be integrated with Git for version control to manage and track changes in automation scripts and test files.

How can I master Playwright for advanced automation tasks?

A: To master Playwright for advanced automation tasks, it is recommended to explore advanced features, APIs, and best practices provided by the Playwright team and community.

What is async in Playwright?

A: In the Playwright framework, async ({page}) signifies a function that operates asynchronously, accepting an argument named page that denotes a web page. The use of async indicates that the function is designed to execute without hindering the concurrent running of other scripts.

What Is Playwright Logging?

Logging in Playwright refers to capturing and displaying information about the browser's activities during a test run. This can include network requests, API calls, console messages, errors, and other events that occur while Playwright scripts are executing. Logging is crucial for debugging and understanding the behavior of web applications during automated testing.

Speed up the entire testing process now

Automate web app testing easier than ever. Without excessive costs. Faster than coding. Free forever.

Dominik Szahidewicz

Software Developer

Application Consultant working as a Tech Writer https://www.linkedin.com/in/dominikdurejko/

Don't miss any updates
Get more tips and product related content. Zero spam.