Getting Started With Playwright Recorder
Sparsh Kesari
Posted On: November 28, 2024
119675 Views
17 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.
TABLE OF CONTENTS
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.
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:
|
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:
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):
1 |
npx playwright test addToCart.spec.ts |
If you want to run the test with a visible browser window (headed mode), you can use this command instead
1 |
npx playwright test addToCart.spec.ts --headed |
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:
1 |
npx playwright show-report |
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.
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.
-
- 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.
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.
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:
|
Below are the steps to implement the above test scenario.
Step 1: Open a terminal and run the following command:
1 |
npx playwright codegen https://ecommerce-playground.lambdatest.io |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import { test, expect } from '@playwright/test'; test('test', async ({ page }) => { // Navigate to the LambdaTest e-commerce playground site await page.goto('https://ecommerce-playground.lambdatest.io/'); // Locate and click the search textbox to enter search criteria await page.getByRole('textbox', { name: 'Search For Products' }).click(); // Type "ipod" in the search textbox to look for the product await page.getByRole('textbox', { name: 'Search For Products' }).fill('ipod'); // Click the search button to initiate the product search await page.getByRole('button', { name: 'Search' }).click(); // Set the filter field in the filter panel await page.locator('#mz-filter-panel-0-0').getByPlaceholder('Minimum Price').click(); await page.locator('#mz-filter-panel-0-0').getByPlaceholder('Minimum Price').fill('100'); await page.locator('#mz-filter-panel-0-0').getByPlaceholder('Maximum Price').click(); await page.locator('#mz-filter-panel-0-0').getByPlaceholder('Maximum Price').fill('150'); await page.locator('#mz-filter-panel-0-0').getByPlaceholder('Maximum Price').press('Enter'); // Click on the iPod Classic product from the search results await page.locator('#mz-product-grid-image-80-212469').click(); // Click the "Add to Cart" button to add the iPod Classic to the shopping cart await page.getByRole('button', { name: 'Add to Cart' }).click(); // Assert that a notification is visible, indicating the product was added to the cart successfully await expect(page.locator('#notification-box-top')).toBeVisible(); // Click on the "Checkout" link to proceed to the checkout page await page.getByRole('link', { name: 'Checkout ' }).click(); // Verify that the iPod Classic is listed in the cart on the checkout page await expect(page.locator('#checkout-cart').getByText('iPod Classic')).toBeVisible(); // Confirm that the price displayed for the iPod Classic is $122.00 await expect(page.getByRole('cell', { name: '$122.00' }).nth(2)).toBeVisible(); }) |
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:
1 |
await expect(page.locator('.product-title')).toHaveText('ipod'); |
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:
1 |
npx playwright test productFilterCheckout.spec.ts |
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:
1 |
npx playwright codegen --viewport-size=800,600 https://ecommerce-playground.lambdatest.io/ |
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:
1 |
npx playwright codegen --device="iPhone 13" https://ecommerce-playground.lambdatest.io/ |
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:
1 |
npx playwright codegen --color-scheme=light https://playwright.dev |
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:
1 |
npx playwright codegen --timezone="Europe/Rome" --geolocation="41.890221,12.492348" --lang="it-IT" https://bing.com/maps |
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.
1 |
npx playwright codegen github.com/microsoft/playwright --save-storage=auth.json |
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.
1 |
npx playwright codegen --save-storage=auth.tson ecommerce-playground.lambdatest.io/ |
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.
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:
- Go to your LambdaTest Account Settings > Password & Security to obtain your username and access key.
- Use the LambdaTest Automation Capabilities Generator to configure browser name, platform name, version, and additional options like storage state, geolocation, and more.
- Add the following code to set up your browser, user credentials, and test configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const capabilities = { browserName: "Chrome", // Options: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox`, `pw-webkit` browserVersion: "latest", "LT:Options": { platform: "Windows 10", build: "Playwright Build", name: "Playwright Test", user: "your-user", accessKey: "your-key", }, }; const browser = await chromium.connect( `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}` ); const page = await browser.newPage(); await page.goto('https://ecommerce-playground.lambdatest.io/'); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import { test, expect, chromium } from '@playwright/test'; const capabilities = { browserName: "Chrome", // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit` browserVersion: "latest", "LT:Options": { platform: "Windows 10", build: "Playwright Build", name: "Playwright Test", user: "LT_USERNAME", accessKey: "LT_ACCESSKEY", }, }; test('test', async ({ }) => { const browser = await chromium.connect(`wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`) const page = await browser.newPage() await page.goto('https://ecommerce-playground.lambdatest.io/'); await page.getByRole('button', { name: 'Shop by Category' }).click(); await page.getByRole('link', { name: 'Laptops & Notebooks' }).click(); await page.getByRole('link', { name: 'HTC Touch HD HTC Touch HD HTC' }).click(); await page.getByRole('button', { name: 'Add to Cart' }).click(); await expect(page.locator('#notification-box-top')).toBeVisible(); }); |
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:
1 |
npx playwright test |
Result:
Once complete, you can view detailed reports of your test execution on the 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.
Got Questions? Drop them on LambdaTest Community. Visit now