Playwright JavaScript Tutorial – DZone

Playwright is an open-source automation library for web browsers developed by Microsoft and primarily used for automating interactions with web browsers like Chromium, Firefox, and Webkit-based browsers. It provides high-level APIs for browser automation, making it easy to perform actions such as clicking buttons, filling out forms, and navigating between pages. 

It also supports advanced features like intercepting network requests, emulating mobile devices, and taking screenshots. Playwright is an end-to-end testing framework that is slowly gaining popularity in the market.

Why Playwright Framework?

The current trend of Playwright on GitHub shows the growing popularity of the Playwright framework (50.4k Star, 2.5k Fork, 99+ Releases).

In the NPM trends, it’s clear that Playwright is gaining popularity in the market.

Benefits of Using Playwright

There are several reasons why Playwright is a good choice for browser automation:

Cross-browser Support

Playwright supports multiple browsers, including Chromium, Firefox, and Safari, making it easier for developers to test their web applications across different platforms and devices.

This means you can write a single automation script and run it across multiple browsers without worrying about browser-specific differences.

Speed and Reliability

Playwright is designed to be fast and reliable, using a powerful architecture that separates the automation code from the browser process, making it more stable and less prone to crashes. Playwright’s API is designed to be intuitive and easy to use, making it ideal for beginners and experienced developers.

Comprehensive API

Playwright has a comprehensive API that covers all aspects of browser automation. It provides methods for interacting with web pages, handling cookies and sessions, and navigating through pages.

Community Support

Playwright has a growing community of developers who contribute to its development, share their knowledge, and provide support to other developers. This means you can get help and advice from other developers when encountering problems.

Trace Viewer

Playwright Trace Viewer is a powerful tool that helps you diagnose and debug issues in your Playwright automation scripts. It provides a visual representation of the actions taken by the Playwright during test execution, along with detailed timing and performance information.

CodeGen

Code generation with Playwright can be a helpful tool for developers who are new to Playwright or need to quickly generate automation code snippets based on their interactions with a web page. It can accelerate the process of creating automation scripts and improve the efficiency of web testing and web scraping tasks.

Why Playwright With JavaScript?

JavaScript is a high-level, interpreted programming language used for web development, server-side programming, and other applications. It is a versatile language used for various purposes, including web development, server-side programming, mobile app development, game development, and more. It is often used in conjunction with popular frameworks and libraries such as React, Angular, and Vue.js to create complex web applications.

It is also a popular language for QA automation because it provides a flexible and powerful toolset for testing web applications. With JavaScript, developers can write automated tests for web applications that run in the browser, such as end-to-end tests, integration tests, and unit tests.

There are several reasons why Playwright with JavaScript is a great choice for browser automation:

Familiarity

Many developers are already familiar with JavaScript, making it easy to get started with Playwright. This also means developers can leverage existing JavaScript libraries and tools when writing automated tests.

Debugging

Debugging automated tests can be challenging, but using Playwright with JavaScript makes it easier to debug tests in the browser’s developer tools. This allows developers/testers to see what is happening in the browser during the test, making diagnosing and fixing issues easier.

Cross-Platform Support

Playwright supports multiple operating systems, including Windows, macOS, and Linux. JavaScript is a cross-platform language, so developers/testers can use it to write tests that can be run across the platform and cross-browser.

Automation

JavaScript is a flexible language that can be used to write different types of automated tests, including unit tests, integration tests, and end-to-end tests. Playwright provides a high-level API that can be used to write tests for different types of applications, such as single-page applications and progressive web applications.

Robustness

Playwright provides a reliable and robust testing framework that allows you to write end-to-end tests for web applications. It provides a robust set of APIs that can handle complex browser interactions, such as handling popups, iframes, and network requests.  

Asynchronous Programming

JavaScript’s asynchronous programming model is well-suited for browser automation, where there are often multiple actions happening simultaneously. Playwright uses promises to handle asynchronous actions, which makes it easy to write code that is both readable and efficient.

Expressive Syntax

JavaScript has a clear and concise syntax, which makes it easy to write code that is both readable and expressive. This is important for automated tests, where code needs to be easy to understand and maintain.

Test Framework Integration

Playwright is designed to be integrated with popular testing frameworks such as Jest and Mocha, which are commonly used for JavaScript testing. This allows you to seamlessly incorporate Playwright scripts into your existing testing workflows, making it easier to write end-to-end tests or perform regression testing for web applications.

Playwright Architecture

To understand the Playwright’s architecture, the best way is to compare it with Selenium. 

In Selenium Architecture, HTTP requests are used to interact with the web application. Once a request is sent to the web server, the server will process the request and send a response back to the Selenium WebDriver.

The HTTP connection is typically terminated after the response is received, which means that the connection between the Selenium WebDriver and the web server is closed. This is because HTTP is a stateless protocol, which means that each request and response is independent of any previous requests or responses.

For example, if the test involves clicking a button on a web page, Selenium WebDriver will send an HTTP request to the webserver to simulate the button click. Once the web server processes the request and sends back the response, the HTTP connection will be terminated.

Selenium WebDriver will send an HTTP request to the webserver to simulate the button click.

In Playwright Architecture, just like Selenium, HTTP requests are used to interact with the web application. But Playwright also supports WebSockets, which allow for real-time, bidirectional communication between the web application and the automation script.

Web Socket Connection

Unlike HTTP, WebSockets are not stateless, and the connection remains open after the initial handshake between the client (Playwright) and the server (web application). This means that the WebSocket connection is not terminated after getting a response and can continue to send and receive messages in real time, and it will remain open until either the client or server terminates the connection.

Features of Playwright

Playwright is a powerful automation tool for web applications that provides a wide range of features for developers and QA engineers. Here are some of the key features of Playwright:

Cross-Language

Playwright is a cross-language automation tool for web applications. It supports automation in several programming languages, such as JavaScript, TypeScript, Python, Java, and C#. This cross-language support allows developers and QA engineers to use their preferred programming language and tools to write tests.

Cross-Browser/Platform

Playwright supports all modern rendering engines, including Chromium, WebKit, and Firefox. Playwright is a cross-platform automation tool for web applications. It supports automation on Windows, macOS, and Linux operating systems, making it easy to run tests on different environments.

Auto-Wait

One of its key features is the auto-wait functionality, which allows Playwright to automatically wait for elements to be ready before performing actions on them. Auto-wait is enabled by default in Playwright and can be customized using the setDefaultTimeout method of the Playwright class. This method sets the default timeout for waiting for an element to appear or become visible.

Intercepting Network Requests

Playwright allows for intercepting and modifying network requests and responses, enabling powerful testing scenarios such as mocking API responses or capturing network traffic for analysis.

Device Emulation

Playwright allows you to emulate different devices, such as mobile phones, tablets, and desktops, making it easy to test the responsiveness of web pages across different devices.

Screenshot and Video Capture: Playwright provides APIs for capturing screenshots and recording videos of web pages, allowing you to visually validate the state of web pages during automation tests.

Assertion

Playwright is compatible with various testing frameworks that provide built-in assertion libraries, such as Jest, Mocha, and Jasmine. These frameworks allow you to write and execute tests that include assertions on various conditions, such as element existence, text content, visibility, and more.

Codegen

Codegen is used in Playwright to generate code for various programming languages such as JavaScript, Python, and C#. Codegen is useful when working with Playwright because it can generate code that follows best practices and reduces the amount of manual coding required.

Playwright Inspector

Playwright Inspector is a feature of the Playwright automation library that allows you to debug and troubleshoot your Playwright scripts. It provides an interactive graphical user interface (GUI) that lets you inspect the state of the browser and the page, interact with page elements, and debug your scripts.

Test Frames

Playwright provides built-in methods to interact with frames in a web page during automation testing. You can use the frame method of the Page object to access and manipulate frames.

Shadow DOM

Playwright CSS and Text Engines, by default, penetrate the Shadow DOM. This makes it easy to find shadow elements and allows you to interact with them similarly to regular DOM elements.

Multiple Tabs and Cross-Origin

You can automate Tabs and Cross-origin in Playwright by creating scenarios with different contexts for different users and running them against your server, all in one test.

Reporting

Playwright provides built-in reporters that you can use to generate reports for your tests. These reporters help you to visualize and understand the results of your tests in a better way. Here are the reporters available in Playwright: ‘list,” dot,” line,” junit,’ and ‘HTML.’

Set Up Playwright With JavaScript

In this section, we will take a look at how to install and configure Playwright and what benefits they offer in terms of installation and setup.

There are two ways of installing the Playwright:

Using the init command

Step 1: Set Up Project 

To get started with Playwright, you’ll need to create a new JavaScript project. You can do this by running the following commands in your terminal.

mkdir playwrights_with_JavaScript

cd playwrights_with_JavaScript

npm init -y

This will create a new directory called “playwrights_with_JavaScript” and initialize a new npm project inside it.

Step 2: Playwright Installation

You’ll need to install Playwright as a dependency of your project. You can do this by running the following command in your terminal.

npm init playwright@latest

After installation, the latest version of Playwright is added as a development dependency to your project.

After installation, we can see that Playwright (version 1.31.2) is installed.

{

 "name": "playwrights_with_javascript",

 "version": "1.0.0",

 "description": "",

 "main": "index.js",

 "scripts": {

   "test": "echo "Error: no test specified" && exit 1"

 },

 "keywords": [],

 "author": "",

 "license": "ISC",

 "devDependencies": {

   "playwright": "^1.31.2"

 }

}

Using the VS Code Extension

Create a folder, e.g., playwright_javascripts_1.31.

Open the folder in VS Code. 

Search Playwright extension in VS Code and install it.

Now Search “Playwright” and Click on Test: Install Playwright.

Finally, click on the OK button.

Once you click on the “OK” button. Installation of Playwright starts and can be seen in the below screenshot after the final installation.

Type of Testing Using Playwright

You can use Playwright for various types of testing using Playwright, including UI Testing, API Testing, Visual Testing, Accessibility Testing, and Component Testing. Each type of testing is explained in detail below with examples.

Playwright UI Testing With JavaScript

With Playwright, you can simulate user interactions such as clicking, filling out forms, and navigating between pages to test the functionality of your web application.

Let’s take an example of UI automation for site.

Use Case: 

Open the site  

And search the data. 

Detail of Use Case:

Let’s create the first spec with the name uiTest.spec.js under. 

In the below test case: 

  • Open the site 
  • Clicking on ‘Mega Menu’ -> Desktop 
  • Click on ‘Palm Treo Pro’.
  • Add item ‘Palm Treo Pro’ into the Cart.
  • Finally, verify item ‘Palm Treo Pro’ should display.
input”)).toHaveValue(“1″)

});
” data-lang=”text/javascript”>

const { test, expect } = require("@playwright/test");

test("Search the text 'Palm Treo Pro  ", async ({ page }) => {

await page.goto('https://ecommerce-playground.lambdatest.io/');

await page.locator("span.title", {hasText: 'Mega Menu' }).hover()

await page.locator("a[title=Desktop]").click();

await page.locator("div.carousel-item.active > img[title="Palm Treo Pro"]").click()

await page.locator("#container button[title="Add to Cart"]").click();

await page.locator("a.btn.btn-primary.btn-block",{hasText: 'View Cart'}).click()

await expect(page.locator("td.text-left", {hasText: 'Palm Treo Pro'})).toBeVisible()

await expect(page.locator("div[class$='flex-nowrap'] > input")).toHaveValue("1")

});

In the above code, we have used several locators. Let’s discuss these locators.

Menu option Mega Menu can be located under the span with the text “Mega Menu.”

We can locate the Computer type “Desktop” by the locator title.

We can locate the Computer type "Desktop" by the locator title.

The locator to click on “Palm Treo Pro” can be achieved button class ‘.container button’ by adding the title of the product.

The locator to click on "Palm Treo Pro" can be achieved button class '.container button' by adding the title of the product.

The locator for clicking on “Add to Cart” can be located by button class with the title of the button.   

The locator for clicking on "Add to Cart" can be located by button class with the title of the button.

Locate “View Cart” can be located by the class of the button with the text “View Cart.”

Locate "View Cart" can be located by the class of the button with the text "View Cart."

Product quantity can be located by class .flex-nowrap.

Product quantity can be located by class .flex-nowrap.

Run the Test Case

In Playwright now, we can run the test case in UI mode. 

Playwright launched UI mode in version 1.32 In the Playwright UI mode, you can interact with the webpage by clicking on elements and filling in forms. You can also see the generated Playwright code in the right-hand panel.

Run the above command it will open the below screen.

Run the above command it will open the below screen.

Run the test case by clicking on Play (>) icon.

Run the test case by clicking on Play (>) icon.

The test case starts executing can be seen in the below screenshot. In the screenshot, we can see on the left side; all commands are executing line by line.

At the bottom of the Source tab, we can see the complete code, which is executed line by line.

At the bottom of the Source tab, we can see the complete code, which is executed line by line.

Playwright  API Testing With JavaScript

Playwright API testing with JavaScript refers to the process of using the Playwright Node.js library to write automated tests for web applications.

This kind of testing is particularly beneficial for checking API answers, validating data input and output, and confirming the functionality of the application. The response status code, headers, and body can all be verified using a number of built-in assertions that are also provided.

Here are some of the key features of Playwright for API testing:

  • HTTP request interception: Playwright provides the ability to intercept HTTP requests and responses, enabling you to simulate various network scenarios and test your API’s behavior in different situations.
  • Intercepting requests: Playwright allows you to intercept HTTP requests made by your application and respond with custom data or mock responses.
  • Mocking responses: You can use Playwright to create mock responses for specific API requests. This can help you test your application’s behavior under different scenarios.
  • Stubbing responses: With Playwright, you can stub responses for specific API requests. This can help you test how your application behaves when certain API requests return unexpected or erroneous data.
  • Setting headers and cookies: Playwright allows you to set HTTP headers and cookies for API requests, which can be useful for testing authentication and authorization functionality.

API Test Example

For API Testing DEMO purposes, I am taking an example of the site. In the below API testing example, we are covering  CRUD operation using the REST API

GET Request

The GET method is used to retrieve specific data and pass parameters to read code from the API response. In the example below, we are getting specific user data using the GET method and userId.

test("GET API Request with -- Valid 200 Response ", async ({ request }) => {

   const response = await request.get(`${baseurl}/users/2`);

   expect(response.status()).toBe(200);

 });

POST Request

A POST API request is a type of API request that is used to send data to a server. It is often used to create or update resources on the server. In a POST request, the client sends a payload (or request body) to the server, which contains the data that needs to be processed or stored.

Below is the example of a POST request where we are creating the data and then verifying the status should be 201.

 test("POST API Request with -- Valid 201 Response ", async ({ request }) => {

   const response = await request.post(`${baseurl}/users/2`, {

     data: {

       id: 123,

     },

   });

   const responseBody = JSON.parse(await response.text());

   expect(responseBody.id).toBe(123);

   expect(response.status()).toBe(201);

 });

PUT Request

A PUT API request is a type of HTTP request used in RESTful web services for updating or replacing an existing resource on the server. In a PUT request, the client sends a payload (or request body) to the server, which contains the updated representation of the resource.

Below is the example of a PUT request where we are updating the id and then verifying the status should be 200.

test("PUT API Request with -- Valid 201 Response ", async ({ request }) => {

   const response = await request.put(`${baseurl}/users/2`, {

     data: {

       id: 245,

     },

   });

   const responseBody = JSON.parse(await response.text());

   expect(responseBody.id).toBe(245);

   expect(response.status()).toBe(200);

 });

DELETE Request

A DELETE API request is a type of HTTP request used in RESTful web services for deleting a resource on the server. In a DELETE request, the client sends a request to the server to delete a resource identified by a specific URI (Uniform Resource Identifier).

Below is the example where we are deleting the particular id and then verifying the status should be 204.

 test("DELETE API Request with -- Valid 201 Response ", async ({

   request,

 }) => {

   const response = await request.delete(`${baseurl}/users/2`, {});

   expect(response.status()).toBe(204);

 });

Output

In the below screenshot, you can see the output of all four methods.

In the below screenshot, you can see the output of all four methods.

Visual Testing Using Playwright

Playwright has the ability to perform visual testing, which means comparing the expected visual appearance of a web page with the actual appearance after changes have been made.

To perform visual testing using Playwright, you can use the ‘expect’, which allows you to take screenshots of web pages and compare them against reference images. Here’s an example of how to perform visual testing using Playwright:

1. First, we navigate to the web page you want to test.

2. Then, we login into the site with a valid credential.

3. Playwright Test will capture a screenshot of the current page and save it as a baseline screenshot (also known as a golden image) when you run a test. In later testing, fresh screenshots will be taken and compared with the baseline using pixel-by-pixel matching. procedure page.To take a screenshot, use the screenshot() function. Method page.screenshot() is used to capture the image.

As an example, suppose you’ve already created a golden image (reference screenshot), and you want to compare it to the screenshot you just took with Playwright. You can use a snippet of code similar to the one below:

expect(await page.screenshot()).toMatchSnapshot('golden.png')

To save a screenshot, Playwright will utilize the page object and call the screenshot function. Then, it will compare these two screenshots for visual differences using the pixel match library. To fine-tune the pixel matching in your screenshots, use the threshold option. 

For a more complete example, please see the snippet below:

test("Login and Edit account detail  ", async ({ page }) => {

   await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/login');

   await page.fill('input[name="email"]', 'lambdatestnew@yopmail.com');

   await page.fill('input[name="password"]', 'Lambda123');

   await page.click('[value="Login"]')

   const screenshot = await page.screenshot({ path: 'example });

   expect(screenshot).toMatchSnapshot('example.png', { threshold: 0.2 });

});

Output

Accessibility Testing Using Playwright

Accessibility testing is an important part of software development as it ensures that your product can be used by people with disabilities. Playwright can be used for web accessibility testing to ensure that web applications are usable and accessible to people with disabilities. WCAG (Web Content Accessibility Guidelines) is a set of standards developed by the World Wide Web Consortium (W3C) to ensure that web content is accessible to all users, including those with disabilities.

By incorporating Playwright into your accessibility testing process, you can automate the testing of WCAG guidelines and ensure that your web application is accessible to all users, including those with disabilities

Below are the steps for doing accessibility testing for the site.

First, you need to install Playwright and axe-core. You can install them using npm @axe-core/playwright and its dependencies. axe-core is an open-source accessibility testing engine developed by Deque Systems. It provides automated accessibility testing capabilities that can be integrated into web applications or testing frameworks.

Run Command : npm install @axe-core/playwright

Create the Playwright’s Script.

const { test, expect } = require("@playwright/test");

const AxeBuilder = require('@axe-core/playwright').default; 

test('Accessibility testing : Scanning the entire page ', async ({ page }) => {

     await page.goto('https://ecommerce-playground.lambdatest.io/'); 

     const accessibilityScanResults = await new AxeBuilder({ page }).analyze(); 

     expect(accessibilityScanResults.violations).toEqual([]); 

});

Code Walkthrough :

First, we Import the package @axe-core/playwright. After providing the URL, we can use Method AxeBuilder.analyze() to run the accessibility scan against the page. Finally, in the last step, verify that there are no violations in the returned scan results.

Output

In the below screenshot, you can see that there are more than 1000 accessibility violations when we Scan a complete page.

you can see that there are more than 1000 accessibility violations when we Scan a complete page.

Component Testing Using Playwright and JavaScript

Component Testing with Playwright is a testing approach that involves testing individual components or pieces of a web application using Playwright, an open-source tool for automating web browsers.

Set up React Application for Playwright Component Testing

React allows developers to build reusable UI components and manage the state of those components efficiently, making it highly suitable for building interactive and dynamic web applications.

React component testing involves writing automated tests to verify the correctness and expected behavior of React components in isolation, without the need for manual testing. This helps to catch bugs and ensure that components are functioning.

React is a free library that helps programmers create user interfaces quickly. It was developed by Facebook in about 2011 and is hugely popular. It currently receives millions of downloads and is maintained by a large community. The latest version of React is 18, and it’s used by millions of users.

React

Testing React components with Playwright involves setting up a testing environment and writing test cases to ensure that the components behave as expected. Here are the steps to get started:

Let’s setup react component.

Step 1

Run the below command in the terminal.

npx create-react-app react-app

Step 2

In the root directory and run the below command to launch React app.

After running the above command ‘npm start’ react app start with the port.

After running the above command 'npm start' react app start with the port.

You can see in your Visual Studio Code the project has been created successfully. What it looks like is attached below.

 Visual Studio Code the project has been created successfully.

Step 3

Now run the below command.

npm init playwright@latest -- --ct

Once the above command is done below options are displayed to install. Select ‘JavaScript.’

Once react framework is installed successfully, you can see the below screenshot.

Once react framework is installed successfully.

Step 4

Once the above command is executed successfully, you can see Playwright is installed.

you can see Playwright is installed.

Testing React Component Using Playwright

Let’s Create two files App.js, App.spec.js under the src folder.

Let's Create two files App.js, App.spec.js under the src folder.

<App> is the root component of the app. Let’s add the below code under App.js, where it is defined:

import logo from './logo.svg';

import './App.css';

function App() {

 return (

   <div className="App">

     <header className="App-header">

       <img src={logo} className="App-logo" alt="logo" />

       <p>

         Edit <code>src/App.js</code> and save to reload.

       </p>

       <a

         className="App-link"

         href="https://reactjs.org"

         target="_blank"

         rel="noopener noreferrer"

       >

         Learn React

       </a>

     </header>

   </div>

 );

}
export default App;

The next step is to write out the test cases that we want to test and then check if the component works as expected. Add the below code under App.spec.js.

import { test, expect } from '@playwright/experimental-ct-react';

import App from './App';

test.use({ viewport: { width: 500, height: 500 } });

test('Verify the text in React Page ', async ({ mount }) => {

 const component = await mount(<App />);

 await expect(component).toContainText('Learn React');

 await expect(component).toContainText('save to reload');

});

In the code block above, we are writing a test case that renders the App component and then checks to see if there is any text like ‘Learn React’ and ‘save to reload’ on the screen.

Now run the test case using the command ‘npm run test-ct.’

After running the above command, run the below command.

‘npx playwright show-report’

Run Playwright Test Cases on the Local Playwright Grid in the Browser

We have taken the below examples for demo purposes. The steps are explained below:

Example  1:

  1. First, open the site.
  2. Click on Menu “Mega Menu.”
  3. Click on Desktop text from the owned menu.
  4. Click on the particular product.
  5. Add to the card.
  6. Finally, verify the product is added to the card with quantity “1.”
input”)).toHaveValue(“1″)

   });

 })” data-lang=”text/javascript”>

// @ts-check

const { test, expect, chromium } = require("@playwright/test");

test.describe("Open the Site and Serach the data ", () => {

 test("Search the text 'Palm Treo Pro  ", async ({ page }) => {

   await page.goto('https://ecommerce-playground.lambdatest.io/');

   await page.locator("span.title", {hasText: 'Mega Menu' }).hover()

   await page.locator("a[title=Desktop]").click();

   await page.locator("div.carousel-item.active > img[title="Palm Treo Pro"]").click()

   await page.locator("#container button[title="Add to Cart"]").click();

   await page.locator("a.btn.btn-primary.btn-block",{hasText: 'View Cart'}).click()

   await expect(page.locator("td.text-left", {hasText: 'Palm Treo Pro'})).toBeVisible()

   await expect(page.locator("div[class$='flex-nowrap'] > input")).toHaveValue("1")

   });

 })

First  Method to Run Test Case:

To run Playwright test cases on the command line, you can use the playwright test commands:

npx playwright test

Here we are executing the test cases in two browsers. For running the test cases in parallel in two browsers, we have to do the below setting in playwright.config.js. 

In the below screenshot, you can see we have passed two browsers.

 /* Configure projects for major browsers */

 projects: [

   {

     name: 'chromium',

     use: { ...devices['Desktop Chrome'] },

   },

   {

     name: 'firefox',

     use: { ...devices['Desktop Firefox'] },

   },

 ],

When you run npx playwright test, it will execute all the test files (by default, files ending with .spec.js) located in the ./tests directory of your project.

When you run npx playwright test, it will execute all the test files (by default, files ending with .spec.js) located in the ./tests directory of your project./

Run command ‘npx playwright show-report’. In the below screenshot, you can see all test steps are passed in both browsers when we run the test case in the local terminal.

Second  Method to Run Test Case: Another way to run the Playwright test cases using the below command. 

npx playwright test –ui

The npx playwright test –ui command is a way to run end-to-end tests using Playwright’s Test Runner with a graphical user interface (GUI). This command launches a test runner UI that allows you to interactively run and debug your tests.

For example, to run tests in UI mode for a file called example.test.js, you can run the following command: npx playwright test –ui example.test.js.

Let’s execute the test cases uiTest.spec.js  in the local environment by running the command. 

npx playwright test --ui uiTest.spec.js

Example  2:

We have another example for the same site.

Where we are opening the site and verifying user redirect to the correct URL on clicking the link.

Test 1

  1. First, open the site.
  2. Click on the Home link.
  3. Verify user redirect to the correct URL of the Home page.

Test 2

  1. First, open the site.
  2. Click on the Blog link.
  3. Verify user redirect to the correct URL of the Blog page.
test.describe("Verify the links in Landing Page ", () => {

   test.beforeEach(async ({ page }) => {

       await page.goto("https://ecommerce-playground.lambdatest.io/");

     });

   test("Open the Site and Click on  Home link and verify user re-direct to correct url", async ({page }) => {

     await page.locator('span:has-text("Home")').click();

     await expect(page).toHaveURL(

       "https://ecommerce-playground.lambdatest.io/index.php?route=common/home"

     );

   });

   test("Open the Site and click on Blog Link and verify user re-direct to correct url", async ({ page }) => {

     await page.locator("#widget-navbar-217834 >> text=Blog").click();

     await expect(page).toHaveURL(

       "https://ecommerce-playground.lambdatest.io/index.php?route=extension/maza/blog/home"

     );

   });

});

We can execute the above code in UI using the below commands in two browsers, Firefox and Chrome.

npx playwright test uiTest.spec.js

Another way to execute the test cases using the below command, which opens the runner from that runner; we can run the particular test case.

npx playwright test –ui

Let’s Execute the spec file ‘uiTest.spec.js.’

Let's Execute the spec file 'uiTest.spec.js.'

Let's Execute the spec file 'uiTest.spec.js.'

Run Playwright Test on the Cloud Grid?

Running your Playwright test on the cloud refers to the process of executing your Playwright test scripts on virtual machines or containers that are hosted on remote servers provided by cloud computing platforms.

There are several cloud-based testing services that allow you to run your Playwright tests on a variety of browsers and operating systems. These services offer pre-configured virtual machines and provide a web interface to run and manage your tests. 

To run your Playwright tests on LambdaTest, you need to create a LambdaTest account, configure your testing environment by selecting the browser and operating system configurations you want to test against, and upload your test scripts to the platform.

There are several benefits of running your Playwright tests on the cloud, which include: 

  • Scalability: With cloud-based infrastructure, you can easily scale your testing environment up or down depending on your testing needs. 
  • Flexibility: The cloud provides access to a wide range of browser and operating system configurations, allowing you to test your web application on various platforms.
  • Cost-effectiveness: Running your Playwright tests on the cloud can be more cost-effective than maintaining your own hardware and software infrastructure.
  • Parallel testing: Cloud-based testing platforms allow you to run your Playwright tests in parallel, which can significantly reduce the time it takes to complete your test suite.
  • Increased test coverage: With access to a wide range of browser and operating system configurations, you can easily increase your test coverage and identify issues that may not be apparent on a single platform.

Configure the Playwright Test on the Cloud Grid

You need to configure your browsers to point to the existing session before launching and configuring your capabilities. In this case, I have set up the platform, build, name, user, and access key attached below.

In the below code, you can see we have configured two browsers (Chrome,Ms Edge) with a different platform.

const capabilities = [

 {

   browserName: "Chrome", // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`

   browserVersion: "latest",

   "LT:Options": {

     platform: "Windows 11",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on Windows 11 - Chrome",

      user: "username",

     accessKey: "accesskey",

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: "MicrosoftEdge",

   browserVersion: "latest",

   "LT:Options": {

     platform: "Windows 11",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on Windows 8 - MicrosoftEdge",

     user: "username",

     accessKey: "accesskey",

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: "Chrome",

   browserVersion: "latest",

   "LT:Options": {

     platform: "MacOS Big sur",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on MacOS Big sur - Chrome",

     user: "username",

     accessKey: "accesskey",

     network: true,

     video: true,

     console: true,

   },

 },

];

And then, on my test, launching the browser to connect to the endpoint:

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/');

Below is the final code to execute the test cases in the cloud.

Example of code walkthrough:

  1. First, open the site.
  2. Click on Menu “Mega Menu.”
  3. Click on Desktop text from the owned menu.
  4. Click on the particular product. 
  5. Add to the card.
  6. Finally, verify the product is added to the card with quantity “1”.

File name: UITest_RunIn-parallel.js

input”)).toHaveValue(

   “1”

 );

 await browser.close();

};

// Capabilities array for with the respective configuration for the parallel tests

const capabilities = [

 {

   browserName: “Chrome”, // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`

   browserVersion: “latest”,

   “LT:Options”: {

     platform: “Windows 11”,

     build: “Playwright Sample Build”,

     name: “Playwright Sample Test on Windows 11 – Chrome”,

     user: “Username”,

     accessKey: “accessKey”,

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: “MicrosoftEdge”,

   browserVersion: “latest”,

   “LT:Options”: {

     platform: “Windows 11”,

     build: “Playwright Sample Build”,

     name: “Playwright Sample Test on Windows 8 – MicrosoftEdge”,

     user: “Username”,

     accessKey: “accessKey”,

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: “Chrome”,

   browserVersion: “latest”,

   “LT:Options”: {

     platform: “MacOS Big sur”,

     build: “Playwright Sample Build”,

     name: “Playwright Sample Test on MacOS Big sur – Chrome”,

     user: “Username”,

     accessKey: “accessKey”,

     network: true,

     video: true,

     console: true,

   },

 },

];

capabilities.forEach(async (capability) => {

 await parallelTests(capability);

});” data-lang=”text/javascript”>

const { chromium } = require("playwright");

const { expect } = require("@playwright/test");

const parallelTests = async (capability) => {

 console.log("Initialising test:: ", capability["LT:Options"]["name"]);

 const browser = await chromium.connect({

   wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(

     JSON.stringify(capability)

   )}`,

 });

 const page = await browser.newPage();

 await page.goto("https://ecommerce-playground.lambdatest.io/");

 await page.locator("span.title", { hasText: "Mega Menu" }).hover();

 await page.locator("a[title=Desktop]").click();

 await page

   .locator("div.carousel-item.active > img[title="Palm Treo Pro"]")

   .click();

 await page.locator("#container button[title="Add to Cart"]").click();

 await page

   .locator("a.btn.btn-primary.btn-block", { hasText: "View Cart" })

   .click();

 await expect(

   page.locator("td.text-left", { hasText: "Palm Treo Pro" })

 ).toBeVisible();

 await expect(page.locator("div[class$='flex-nowrap'] > input")).toHaveValue(

   "1"

 );

 await browser.close();

};

// Capabilities array for with the respective configuration for the parallel tests

const capabilities = [

 {

   browserName: "Chrome", // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`

   browserVersion: "latest",

   "LT:Options": {

     platform: "Windows 11",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on Windows 11 - Chrome",

     user: "Username",

     accessKey: "accessKey",

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: "MicrosoftEdge",

   browserVersion: "latest",

   "LT:Options": {

     platform: "Windows 11",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on Windows 8 - MicrosoftEdge",

     user: "Username",

     accessKey: "accessKey",

     network: true,

     video: true,

     console: true,

   },

 },

 {

   browserName: "Chrome",

   browserVersion: "latest",

   "LT:Options": {

     platform: "MacOS Big sur",

     build: "Playwright Sample Build",

     name: "Playwright Sample Test on MacOS Big sur - Chrome",

     user: "Username",

     accessKey: "accessKey",

     network: true,

     video: true,

     console: true,

   },

 },

];

capabilities.forEach(async (capability) => {

 await parallelTests(capability);

});

To run the test case, you have to run the below command.

node UiTest_RunIn-parallel.js

node UiTest_RunIn-parallel.js

View Your Playwright Test Results

When Playwright tests are executed on the platform, the results are displayed in the LambdaTest Automation Dashboard. 

In the below screenshot, you can see the test case start executing on different platforms. 

Finally, you can see test case is executed.

Wrapping Up

In conclusion, Automation testing using Playwright and JavaScript can significantly improve the efficiency and effectiveness of software testing. Playwright is a powerful and user-friendly automation tool that enables you to automate web browsers with ease. The combination of Playwright and JavaScript allows you to create automated tests that can be run repeatedly and consistently, saving you time and effort.


Source link