Getting Started With Playwright Recorder

Sparsh Kesari

Posted On: November 28, 2024

view count44398 Views

Read time16 Min Read

Test automation can be time-consuming, even for the most experienced programmers. Developing and maintaining complex scripts requires extreme accuracy, which can slow down workflows, especially as the number of tests increases with project size. While non-technical testers may struggle with automation, even skilled testers find it challenging to balance speed with accuracy.

This is where automation testing tools like Playwright help you record tests using a simple GUI, which automatically generates code, thus speeding up the testing process. The Playwright recorder feature simplifies test creation and auto-generates scripts that can be fine-tuned for flexibility and scalability.

What Is a Playwright Recorder?

Playwright recorder is a tool that allows you to easily record tests by capturing your interactions with web applications. It generates code based on the actions performed, helping both beginners and experienced developers create test scripts quickly. The generated code is reusable and compatible with multiple browsers, making it easier to automate testing for web applications.

This tool offers two ways to record tests, catering to different workflows and preferences:

  • Recording Tests With VS Code Extension: The Playwright Visual Studio Code extension allows users to record and edit tests entirely within the IDE. It enables developers to record tests while building or maintaining code, keeping the entire process within their development environment.
  • Recording Tests With Playwright Inspector: The Playwright Inspector is a tool designed to record tests interactively as a Playwright session is executed. It provides an intuitive view of the application under test while recording interactions such as clicks, form inputs, and navigation.
Info Note

Run Playwright tests across 3000+ browsers and OS combinations. Try LambdaTest Today!

Now that you’re familiar with what the Playwright recorder is and how you can record your tests, let’s explore each in detail to enhance your understanding of using the Playwright recorder.

Playwright Recording With VS Code Extension

You can record your tests using the Playwright VS Code extension, which streamlines test creation by enabling seamless recording, editing, and execution within the IDE.

To better understand how to record with the Playwright extension, let’s walk through a common test scenario, recording a product search and checkout flow on the LambdaTest eCommerce Playground website.

Test Scenario:

  1. Go to the page URL defined before.
  2. Click on “Shop by Category”.
  3. Select the “Laptops & Notebook” Category.
  4. Add the product ”HTC Touch HD” to the cart.
  5. Assert if the “Add to Cart” popup is visible.

Below is the implementation of the above test scenario.

Prerequisite: Ensure Playwright is installed in your project and that your project folder is open in VS Code. For detailed instructions on installing Playwright, follow this guide on how to install Playwright and get detailed insights.

Once the Playwright prerequisites are in place, you can follow the steps given below to get started with the Playwright recorder.

Step 1: First, you must install the Playwright extension from the VS Code Marketplace. This extension gives you Playwright-specific tools like test recording and running features fully integrated into your development workspace.

Step 2: After installing the Playwright extension, open your project in VS Code and navigate to the TEST EXPLORER view to manage and run your tests. To record a test, click the Record new button in the testing sidebar.

This will create a test-1.spec.ts file and open a browser window. The browser window will record your interactions with the website, capturing actions such as clicks, form entries, and navigation. It will then generate the corresponding test script in real time within your test file.

In the browser, go to the URL you wish to test and start clicking around to record your user actions according to the test scenario.

Step 3: To verify user behavior, use the recorder’s toolbar to capture assertions while recording. This allows you to easily add checks for visibility, text content, and values directly during the test creation process. For example, you can add an assertion to verify if the Add to Cart popup is visible after clicking the Add to Cart button.

Step 4: Once you have completed the test scenario, the Playwright will automatically generate a test script based on your actions. Save the generated script as a .spec.ts file (for example, addToCart.spec.ts).

Here’s an example of what the generated code might look like:

example of what the generated code might look like

Step 5: To execute your test script, go to the TEST EXPLORER pane and click the play button next to the test file or spec file you want to run. The test will execute in headless mode (without a visible browser), and the results will be displayed in the TEST EXPLORER.

If you’d like to run the test with a visible browser, you can enable the Show browser checkbox or Show trace viewer checkbox, then rerun the tests using the play button next to your test file.

Step 6: Open a terminal in VS Code and run the following command to execute the test in headless mode (i.e., without opening a visible browser window):

If you want to run the test with a visible browser window (headed mode), you can use this command instead

Step 7: If a test case fails, an automatic report page will appear to display details of the failed tests. To view the report of your most recent test execution, you can run the following command in your terminal:

command in your terminal

Customizing and Debugging Your Test With Playwright Recorder

After recording and reviewing your test script, you might want to tweak it further by adding assertions or custom logic. Playwright offers functionalities to record assertions and generate locators, making it easier to customize and debug your test scripts.

    • Generating Locators:

Playwright recorder simplifies the process of generating locators using the Pick locator option.

Step 1: Click on the Pick locator button from the testing sidebar, then hover over elements in the browser window. The locator will be highlighted under each element.

Pick locator

Step 2: Click the desired element, and the locator will appear in the Pick locator box in VS Code.

Step 3: Press Enter to copy the locator to your clipboard and paste it into your code, or press Escape to cancel.

copy the locator

    • Recording Test at Cursor:

To record additional actions at a specific point in your test:

Step 1: Move the cursor in your test file to where you want to record new actions.

Step 2: Click the Record at cursor button from the testing sidebar. If the browser window is not open, run the test with Show browser enabled, and then click Record at cursor.

Record at cursor

Step 3: In the browser window, perform the desired actions.

Step 4: The newly recorded actions will automatically appear at the cursor position in your test file in VS Code.

test file in VS Code

By leveraging these Playwright recorder features, you can efficiently customize and debug your test scripts.

Playwright Recording With the Inspector

The Playwright Inspector is another powerful tool that observes your interactions with a website and generates tests. By running the codegen command, Playwright opens two windows side by side:

  • Browser Window: This is where you interact with the website.
  • Playwright Inspector Window: This records your actions in real-time, generating Playwright code that you can copy and use in your test files.

The codegen command simplifies the process of creating scripts by capturing user interactions and converting them into executable code.

To record a test scenario using the codegen command, let’s take a detailed example involving multiple interactions and assertions. The scenario simulates a user journey of searching for a product, applying a filter, adding the product to the cart, and verifying the checkout process.

Test Scenario:

  1. Navigate to the Homepage.
  2. Type “iPod” in the search bar and press enter.
  3. Set a price range to narrow down the results.
  4. Click on a product that matches the criteria.
  5. Add the product to the cart.
  6. Ensure the product price matches the cart total.
  7. Proceed to checkout.

Below are the steps to implement the above test scenario.

Step 1: Open a terminal and run the following command:

This will open two windows:

  • A browser window where you can interact with the website.
  • The Playwright Inspector tracks your actions and generates code in real-time.

Step 2: Interact with the browser to follow the test scenario steps (e.g., navigating, searching for a product, applying filters, and adding to the cart). The Inspector will record and translate these actions into Playwright code automatically.

Step 3: After completing the scenario, review the code generated by the Playwright Inspector. Make any necessary adjustments to enhance the script’s accuracy or readability.

Here’s an example of what the script might look like with added assertions:

Step 4: Enhance the script by adding multiple assertions to verify key elements and conditions, such as:

  • Success message confirmation after adding the product to the cart.
  • Cart total validation to ensure the price matches.
  • Checkout details verification to confirm shipping information and order summary.

To verify the selected product’s name is visible on the product page, add:

You can also include assertions for other elements like product images, descriptions, or ratings.

Step 5: Once satisfied with the recorded and edited test script, save it as a .spec.ts file. For instance, name it: productFilterCheckout.spec.ts

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

Emulating Different Environments With Playwright Codegen

Emulation is a powerful feature in Playwright that replicates various environments, such as devices, viewports, color schemes, and geolocation settings. It ensures applications work seamlessly across diverse user conditions, enabling testers to record realistic user scenarios and generate scripts reflecting actual application behavior.

Emulate Viewport Size

By default, Playwright opens a browser window with a preset viewport size. To test your application under specific viewport dimensions (e.g., smaller or larger screens), use the --viewport-size command with codegen.

To generate tests with a custom viewport size, run the command below:

In the above command:

  • --viewport-size=800,600: Sets the width to 800 pixels and height to 600 pixels.
  • Useful for simulating small-screen desktops or large tablets in landscape orientation.

Emulate Device

Playwright allows you to emulate real devices like smartphones or tablets by using the --device command. This includes setting the appropriate user agent and viewport characteristics to mimic a specific device.

To emulate an iPhone 13, run the command given below:

In the above command:

  • --device="iPhone 13": Sets the viewport size, user agent, and device characteristics to match an iPhone 13.

Emulate Color Scheme

Some websites offer different themes based on the user’s system preferences, such as light mode and dark mode. The Playwright supports emulating these color schemes during test generation using the --color-scheme command.

To emulate light mode, run the command given below:

In the above command:

  • --color-scheme=light: It instructs the Playwright to emulate a light color scheme for the browser session.

Emulate Geolocation, Language, and Timezone

To test localization features like language or time-based behavior, you can use Playwright’s options for geolocation, language, and timezone emulation. This is particularly useful for applications that display location-based information or time-sensitive content.

To emulate the geolocation, language, and timezone, run the command given below:

In the above command:

  • --timezone="Europe/Rome": It sets the simulated timezone to Rome, Italy.
  • --geolocation="41.890221,12.492348": It emulates a location in Rome based on latitude and longitude.
  • --lang="it-IT": It sets the language to Italian.

Locating Authentication State

Playwright lets you save and reuse the authenticated state of a session, which is especially useful for testing scenarios that require login credentials. Using the --save-storage and --load-storage commands, you can record an authentication step once and reuse it in subsequent tests.

To achieve this, you must follow the steps given below:

Step 1: To save cookies, localStorage, and session data, use the --save-storage command. This command launches Playwright in code generation mode, recording your interactions and saving the session data at the end.

Step 2: To run tests from an authenticated state, use the --load-storage command. This loads the saved session data, including cookies and localStorage, allowing you to bypass login and continue testing as an authenticated user.

By restoring the session, you can directly access pages that require log-in, saving time and enabling seamless test generation from a logged-in state.

Tip: Since auth.json contains sensitive information, use it only locally. Make sure to add it to .gitignore or delete it when done.

code

Running Playwright Recorder Tests on Cloud Grid

Scaling tests across multiple platforms and browsers can be challenging with local setups. Cloud-based platforms provide a scalable and reliable solution by offering access to a wide range of browser and OS combinations for efficient cross-browser testing.

One such platform is LambdaTest, an AI-powered test execution platform that simplifies this process by offering test automation with Playwright across 3000+ real web browsers online.

To connect your local Playwright test script and execute it on the LambdaTest cloud platform, follow the steps below:

  1. Go to your LambdaTest Account Settings > Password & Security to obtain your username and access key.
  2. Use the LambdaTest Automation Capabilities Generator to configure browser name, platform name, version, and additional options like storage state, geolocation, and more.
  3. Add the following code to set up your browser, user credentials, and test configuration:

By making minor modifications to your local script and incorporating the necessary capabilities, you can easily run Playwright tests on LambdaTest.

Here is how the entire code will look after adding the necessary capabilities:

github

This setup will connect your Playwright tests to LambdaTest, enabling seamless cross-platform and cross-browser testing.

Output:

To run the above test script, run the command given below:

Result:

Once complete, you can view detailed reports of your test execution on the LambdaTest Dashboard.

LambdaTest Dashboard

Subscribe to the LambdaTest YouTube Channel to get more tutorial videos on Playwright testing.

Conclusion

The Playwright recorder is an invaluable tool for quickly generating test scripts by capturing user interactions with the browser. It streamlines the process of test creation, making it easy for teams to prototype and start testing with minimal effort. While the generated scripts can provide a solid foundation, refining and customizing them is often necessary for better maintainability and to handle complex or dynamic scenarios.

With its ability to easily capture actions across browsers, Playwright offers scalability and flexibility for cross-browser testing. Teams can leverage the Playwright recorder to quickly get started and enhance their automated testing workflows, ensuring a smooth and efficient testing process.

Frequently Asked Questions (FAQs)

What is Playwright Codegen, and how does it help in test automation?

Playwright Codegen is a tool that automatically generates test scripts by recording user interactions with a web application. It simplifies the creation of tests by capturing clicks, form submissions, and other actions and converts them into reusable code, speeding up the test development process.

How do I record tests using Playwright’s VS Code extension?

To record tests with Playwright in VS Code, install the Playwright extension, then use the “Record New” button in the Test Explorer panel. As you interact with the application in the browser, Playwright generates the corresponding test script in real-time, which you can customize and run directly within the IDE.

Can Playwright Codegen generate tests for multiple browsers?

Yes, Playwright Codegen generates cross-browser test scripts compatible with Chromium, Firefox, and WebKit. This allows you to test your application across different browsers and ensure compatibility without additional manual configuration.

How can I emulate different devices using Playwright Codegen?

You can emulate devices with Playwright by using the --device flag, such as --device="iPhone 13". This replicates the device’s screen size, user agent, and other characteristics, allowing you to test how your application behaves on different devices during test creation.

Is it possible to customize the generated test scripts in Playwright?

Yes, Playwright Codegen provides the flexibility to customize the generated scripts. After the initial script is recorded, you can edit it to add custom logic, assertions, and parameterization to suit your specific test scenarios.

Author Profile Author Profile Author Profile

Author’s Profile

Sparsh Kesari

Sparsh Kesari is a software developer specializing in Full Stack Development. He is an Open Source enthusiast and has been part of various programs including GitHub Externship. He has also interned at organizations like GitHub India, RedHat, MeitY, Government of India. He is actively involved in the testing and QA community work as well. In his current position, he works as a Developer Relations Engineer at LambdaTest, exploring and contributing to the testing world.

Blogs: 9



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free