Microsoft Device Playwright for Automated Testing – DZone – Uplaza

Introduction to Playwright Testing

Playwright is a strong and versatile automation library developed by Microsoft. It allows builders and testers to automate net purposes throughout a number of browsers with ease. This information will stroll you thru the fundamentals of utilizing Playwright for check automation, from set up to writing and operating your first assessments. Playwright automation helps Chromium, Firefox, and WebKit, permitting you to check throughout completely different browsers.

On this weblog, we’ll deep dive into the numerous options of Playwright and the way we are able to carry out end-to-end testing with Playwright with detailed examples.

Key Options of Playwright

Under are among the key options of the Playwright testing device:

  1. Cross-browser testing: Playwright helps all main browsers out of the field, together with Chromium, Firefox, and WebKit (Safari). This cross-browser help means that you can write assessments as soon as and run them throughout a number of browsers with none further configuration or setup. Playwright ensures constant conduct and API throughout all supported browsers, making it simpler to take care of and scale your check suite. Playwright gives built-in help for machine emulation utilizing browsers like Safari and Chrome.
  2. Headless and headful modes: Playwright means that you can run assessments in headless mode (with no seen browser window) or headful mode (with a visual browser window). Headless mode is beneficial for operating assessments in CI/CD pipelines. Headful mode is useful for debugging, visible inspection, or when that you must work together with the browser throughout check execution.
  3. Automated ready: Playwright routinely waits for components to be prepared earlier than interacting with them, lowering the chance of check flakiness attributable to timing points. It employs clever ready methods, equivalent to ready for community requests to finish or DOM mutations to happen, guaranteeing that assessments are executed reliably and persistently.
  4. Community interception: Playwright gives highly effective community interception capabilities, permitting you to intercept and modify community requests and responses throughout check execution. This characteristic is beneficial for testing situations involving APIs, mocking responses, simulating community situations, or bypassing authentication mechanisms.
  5. A number of contexts: Playwright means that you can create a number of browser contexts inside a single check run, successfully simulating completely different consumer classes or environments. This characteristic is especially helpful for testing situations involving multi-user interactions, equivalent to chat purposes or collaborative instruments.
  6. Highly effective selectors: Playwright affords a wealthy set of selector methods, together with CSS selectors, XPath, textual content selectors, and extra. It additionally gives superior selector choices, equivalent to dealing with dynamic components, deciding on components primarily based on their visibility or accessibility, and deciding on components inside iframes and shadow DOMs, that are widespread in fashionable net purposes.
  7. Screenshot and video seize: Playwright lets you seize screenshots and document movies of your check runs with a single line of code. This characteristic is invaluable for debugging, visible regression testing, and producing visible artifacts for documentation or reporting functions.
  8. Isolation and parallelism: Playwright gives built-in help for operating assessments in isolation and in parallel. Take a look at isolation ensures that every check run is unbiased and would not intrude with different assessments, stopping state air pollution and bettering check reliability. Parallel check execution can considerably velocity up your check suite by using a number of CPU cores or machines, lowering total check execution time.

Playwright Take a look at Automation Framework

Playwright’s structure is designed to supply a strong, versatile, and high-performance framework for browser automation. Its help for a number of browser engines, remoted browser contexts, and highly effective API makes it a wonderful alternative for net scraping, automated testing, and different browser automation duties. The structure ensures that assessments and scripts are dependable, environment friendly, and simple to take care of.

Credit score: ProgramsBuzz

Key Elements and Processes

1. Consumer Facet (Automation Scripts)

  • Languages supported: Playwright helps JavaScript and TypeScript “natively”, whereas additionally offering “bindings” for Java, Python, and C#  for writing automation scripts.
  • Take a look at script creation: Customers write check scripts of their most popular language. These scripts embody check instances, interplay instructions, and assertions. JSON is usually used for configuration and knowledge alternate.

2. WebSocket Connection

  • Handshake: When a check script is executed, it initiates a connection to the Playwright server (Node.js). This connection includes an preliminary handshake to ascertain communication.
  • Full duplex (bi-directional) communication: As soon as related, there’s a bi-directional communication channel between the consumer and the server. That is important for sending instructions to the browser and receiving responses or occasions in real-time.
  • Open and protracted connection: The WebSocket connection stays open and protracted all through the session, permitting steady interplay between the check scripts and the browser.
  • Connection closure: After check execution, the connection could be closed both by the consumer or the server, marking the tip of the session.

3. Server Facet (Node.js)

  • Node.js server: The server aspect is managed by a Node.js software, which orchestrates the interplay between the consumer scripts and the browsers.
  • Dealing with instructions and occasions: The Node.js server receives instructions from the consumer, processes them, and sends acceptable directions to the browsers. It additionally listens for occasions from the browser and relays them again to the consumer.

4. Browser Automation (CDP and CDP+)

  • CDP (Chrome DevTools Protocol): Playwright makes use of the CDP for interacting with Chromium-based browsers. CDP manages the render, browser, and community processes, that are important for rendering pages, managing browser classes, and dealing with community interactions.
  • CDP+: The picture additionally mentions CDP+ for browsers like Firefox and WebKit (Safari). Playwright extends help to those browsers by utilizing protocols much like CDP, guaranteeing a constant API throughout completely different browsers. Every browser course of (render, browser, community) is managed to simulate consumer interactions precisely.

How Playwright Take a look at Execution Works

  1. The consumer (check script) sends directions to the server over the WebSocket connection.
  2. The server receives these directions and interprets them into instructions that may be understood by the browser situations.
  3. The server communicates with the browser situations utilizing both CDP or CDP+, relying on the necessities.
  4. The browser situations execute the instructions, equivalent to navigating to net pages, interacting with components, or capturing screenshots.
  5. The outcomes or knowledge from the browser situations are despatched again to the server.
  6. The server relays the outcomes or knowledge again to the consumer over the WebSocket connection.

Getting Began With Playwright Testing

Under are the steps for performing Playwright set up on a Home windows machine:

Step 1: Set up of Node.JS

Playwright is code is predicated on Node.js, so we’d like node.js put in in our system, we are able to do that utilizing the official web site and obtain the most recent model (https://nodejs.org/), after putting in or not it’s can validate the set up standing utilizing a command on the terminal.

node -v

npm -v

// These instructions will show put in Node.js and npm variations

Step 2: Create a New Node.js Undertaking

On this step, we’ll create a brand new listing for the playwright undertaking and navigate to it utilizing the terminal.

mkdir my-playwright-project

cd my-playwright-project

npm init -y

The above instructions will create a brand new Node.js undertaking with a `bundle.json` file.

For detailed steps on set up observe the hyperlink.

Folder Construction of Playwright Automation Device

The beneath screenshots show how Playwright creates a default folder hierarchy when it first launches. Under is an in depth description of every of those recordsdata and folders that the Playwright framework has.

playwright testgrid

The picture exhibits the folder construction of a Playwright automation device undertaking. This is a proof of every merchandise within the construction:

  1. .github: This listing sometimes comprises GitHub-specific recordsdata and configurations, equivalent to GitHub Actions workflows.
  2. node_modules: This listing comprises all of the Node.js modules put in for the undertaking. These are the dependencies laid out in bundle.json.
  3. assessments: This listing doubtless comprises the Playwright check recordsdata. These recordsdata outline the assessments that can be executed utilizing Playwright. We usually create a brand new check file on this folder.
  4. tests-examples: This listing comprises instance check recordsdata or templates that can be utilized as references when writing new assessments.
  5. .gitignore: This file specifies which recordsdata and directories ought to be ignored by Git. Generally ignored recordsdata embody node_modules, logs, and construct directories.
  6. package-lock.json: This file is routinely generated and consists of the precise variations of put in dependencies. It ensures that the undertaking is persistently put in throughout completely different environments.
  7. bundle.json: This file comprises metadata in regards to the undertaking, together with its dependencies, scripts, and different configurations. It’s essential for managing the undertaking with Node.js.
  8. playwright.config.js: This configuration file is particular to Playwright. It defines settings and choices for operating Playwright assessments, such because the browser settings, check listing, timeout configurations, and so on.

Create First Script in Playwright With Detailed Instance

Earlier than creating the primary script we have to perceive a couple of ideas in Playwright.

Async and Await

async and await are used to work with asynchronous code in JavaScript. They’re important when coping with operations that take time to finish, equivalent to community requests or file operations.

  • async: This key phrase is used to outline an asynchronous operate.
  • await: This key phrase is used to attend for a Promise to resolve earlier than persevering with execution.

Instance

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

(async () => {
const browser = await chromium.launch();
const web page = await browser.newPage();
await web page.goto('https://www.instance.com');
// Watch for the web page to load and get the title
const title = await web page.title();
console.log(`Web page title: ${title}`);
await browser.shut();
})();

check()

In Playwright’s check runner (@playwright/check), the check is used to outline particular person check instances.

Instance

const { check, count on } = require('@playwright/check');

check('primary check', async ({ web page }) => {
await web page.goto('https://instance.com');
const title = await web page.title();
count on(title).toBe('Instance Area');
});

This instance defines a primary check that navigates to a web page and checks if the title is “Example Domain.”

describe() 

describe is used to group associated assessments collectively. This helps in organizing assessments higher, particularly when you may have numerous assessments.

const { check, count on } = require('@playwright/check');
check.describe('Instance Group', () => {
check('first check', async ({ web page }) => {
await web page.goto('https://instance.com');
const title = await web page.title();
count on(title).toBe('Instance Area');
});

check('second check', async ({ web page }) => {
await web page.goto('https://instance.com');
const content material = await web page.textContent('h1');
count on(content material).toBe('Instance Area');
});
});

Hooks 

Hooks are capabilities which can be executed at particular factors within the check lifecycle. Widespread hooks embody beforeAll, afterAll, beforeEach, and afterEach.

const { check, count on } = require('@playwright/check');

check.describe('Instance Group with Hooks', () => {
check.beforeAll(async () => {
console.log('Setup earlier than all assessments');
});

check.afterAll(async () => {
console.log('Cleanup in spite of everything assessments');
});

check.beforeEach(async ({ web page }) => {
await web page.goto('https://instance.com');
});

check.afterEach(async ({ web page }) => {
await web page.shut();
});

check('check with hooks', async ({ web page }) => {
const title = await web page.title();
count on(title).toBe('Instance Area');
});
});

Assertions 

Assertions are used to confirm that the appliance behaves as anticipated. Playwright makes use of aside from assertions. The count on operate takes an precise worth and gives numerous matcher strategies to claim in opposition to the anticipated worth.

const { check, count on } = require('@playwright/check');

check('assertion check', async ({ web page }) => {
await web page.goto('https://instance.com');
const title = await web page.title();
count on(title).toBe('Instance Area');

const content material = await web page.textContent('h1');
count on(content material).toBe('Instance Area');
});

Automate Your First Playwright Take a look at Case

Let’s create a .spec file ‘testGrid.spec.js’ beneath the folder assessments.

We’re protecting the state of affairs the place the consumer is ready to log in, navigate to the codeless automation part, confirm the navigation to a brand new tab by clicking on the hyperlink ‘Real Device Cloud,’ return to the guardian web page, and sign off efficiently

Let’s take Playwright  testing examples to check end-to-end check situations from login to the location with legitimate credentials, Navigate to the codeless automation part, verifying the navigation to a brand new tab by clicking on the hyperlink ‘Real Device Cloud,’ returning to the guardian web page, and sign off efficiently

Take a look at State of affairs

  1. Go to the Website
  2. Login into the location legitimate credential 
  3. Confirm the consumer is logged in by various the textual content “dashboard”
  4. Click on on the ‘codeless’ hyperlink beneath the automation part
  5. Confirm the textual content “let’s get you started with codeless automation”
  6. Open the hyperlink ‘actual machine cloud’ within the new tab after which again to the guardian web page
  7. Confirm the textual content “selenium” to verify the consumer is again on the guardian web page
  8. Logout from the appliance

Write a easy Playwright check in file ‘testGrid.spec.js’ which is roofed beneath performance for the web site.

const { chromium, check, count on } = require("@playwright/test");

check("Testgrid.io Scenario", async ({ browser }) => {
const context = await browser.newContext();
const web page = await context.newPage();

// 1. Go to the Website https://testgrid.io/
await web page.goto("https://public.testgrid.io/");

// 2. Login into the location with legitimate credentials
await web page.fill('enter[name="email"]', "jarryliurobert@gmail.com");
await web page.fill('enter[name="password"]', "Test@1234");
await web page.click on('button:has-text("Sign in")');
await web page.waitForTimeout(7000);



 // 3. Confirm consumer is logged in by verifying the textual content "Dashboard"
await count on(web page.locator("text=Dashboard")).toBeVisible();

// 4. Click on on 'Codeless' hyperlink beneath Automation part
await web page.click on("text=Codeless");

// 5. Confirm the textual content "Let's get you started with codeless automation"
await count on(
web page.locator("text=Lets get you started with codeless automation")
).toBeVisible();
await web page.click on('[id="testcase_back_button"]');

// 6. Open the hyperlink 'Actual Gadget Cloud' in a brand new tab after which again to the guardian web page
const [newPage] = await Promise.all([
context.waitForEvent("page"),
page.click("text=Real Device Cloud"),
]);
await newPage.waitForLoadState("domcontentloaded");
await newPage.shut();
await web page.bringToFront();

// 7. Confirm the textual content "Selenium" to verify the consumer is again on the guardian web page
await count on(web page.locator("text=Selenium")).toBeVisible();

// 8. Logout from the appliance
await web page.click on('[data-toggle="dropdown"]');
 web page.click on("text=Logout");

await count on(web page.locator("text=Forgot Password?")).toBeVisible();
await context.shut();
});

Code Walkthrough

To know the Playwright testing instance script intimately. Let’s undertake the above code walkthrough.

Imports the required Playwright modules for browser automation, testing, and assertions.

Import Required Modules:
const { chromium, check, count on } = require("@playwright/test");

Defines a check named "Testgrid.io Scenario" that makes use of a browser occasion.

Outline a Take a look at State of affairs:

check("Testgrid.io Scenario", async ({ browser }) => {

Setup Browser Context and Web page: Creates a brand new browser context and a brand new web page inside that context.

const context = await browser.newContext();
const web page = await context.newPage();

Navigate to Testgrid.io: Opens the Testgrid.io web site.

await web page.goto("https://public.testgrid.io/");

Log in to the Website: Fill within the login type along with your e mail and password, click on the sign-in button, and look ahead to 7 seconds.

await web page.fill('enter[name="email"]', "xxxxx@gmail.com");
await web page.fill('enter[name="password"]', "xxxx@1234");
await web page.click on('button:has-text("Sign in")');
await web page.waitForTimeout(7000);

Confirm Profitable Login: Checks if the “Dashboard” textual content is seen, indicating a profitable login.

await count on(web page.locator("text=Dashboard")).toBeVisible();

Navigate to Codeless Automation: Click on on the “Codeless” hyperlink beneath the Automation part.

await web page.click on("text=Codeless");

Confirm Codeless Automation Web page: Confirm the presence of the textual content associated to codeless automation and click on the again button.

Open Actual Gadget Cloud in New Tab: Opens the “Real Device Cloud” hyperlink in a brand new tab, waits for the brand new web page to load, closes the brand new web page, and returns to the unique web page.

const [newPage] = await Promise.all([
context.waitForEvent("page"),
page.click("text=Real Device Cloud"),
]);
await newPage.waitForLoadState("domcontentloaded");
await newPage.shut();
await web page.bringToFront();

Confirm Return to Guardian Web page: Examine if the “Selenium” textual content is seen to verify the consumer is again on the guardian web page.

await count on(web page.locator("text=Selenium")).toBeVisible();

Logout from the Software: Clicks on the dropdown menu, selects “Logout”, and closes the browser context.

await web page.click on('[data-toggle="dropdown"]');
web page.click on("text=Logout");

await count on(web page.locator("text=Forgot Password?")).toBeVisible();
await context.shut();

Execute The Take a look at Circumstances Regionally

To execute the check instances, you should utilize Playwright instructions in your terminal. Playwright helps each headed mode (the place you may see the browser window) and headless mode (the place assessments run within the background with no seen browser window). 

Within the part beneath you will note how we are able to run playwright check automation in headed and headless mode.

Run Take a look at Circumstances in Headed Mode

In headed mode, you may see check instances are executed within the seen browser window.

  • Open your terminal.
  • Navigate to the listing the place your Playwright assessments are positioned.
  • Run the command to execute the assessments in headed mode.

Run the command npx playwright check --ui  or yarn playwright check --ui  as we run the command it’s going to open beneath display. Click on on the .spec file ‘testGrid.spec.js’ to run the check case in headed mode.

After we click on on testGrid.spec.js, the check case begins executing and eventually the check case passes efficiently. 

Under are the screenshots of the check case execution regionally.

Within the ultimate step, the consumer is logged out of the appliance.

Run Take a look at case In Headless Mode

By default, Playwright runs in “headless mode,” the place the browser runs within the background with out opening a visual browser window.

Command to run the check case in headless mode npx playwright check or yarn playwright check.

Run the command: 

‘npx playwright test tests/testGrid.spec.js’. As you execute this command, the check case begins executing in headless mode. 

Within the beneath screenshot, you may see the check case begins executing in headless mode in Chrome browser as soon as execution is accomplished the check instances cross in Chrome.

Run the command ‘npx playwright show-report’ Under is the hooked up HTML report.

Playwright Greatest Practices 

Under are a couple of greatest practices of Playwright. By following these greatest practices, you may streamline your testing course of, improve reliability, and keep code readability:

Leverage Playwright’s Assertions

Playwright gives built-in assertions like toBeVisible, toHaveText, and toHaveURL to validate the appliance state after consumer interactions. This simplifies check logic and improves maintainability.

check('login type is displayed', async ({ web page }) => {
await web page.goto('https://your-app.com/login');
await count on(web page.locator('#username')).toBeVisible();
  await count on(web page.locator('#password')).toBeVisible();

  await count on(web page).toHaveText('Thanks in your order!')
});

Leverage Playwright’s Wait Methods

Playwright affords functionalities like waitForSelector, waitForNavigation, and count on timeouts to make sure components are loaded and prepared earlier than interplay. This improves check reliability.

Instance

Use the await web page.waitForSelector('#submit-button') earlier than clicking the submit button.

Hold Checks Impartial

Every check ought to operate independently, with its personal knowledge, cookies, and native storage. This makes assessments extra dependable and simpler to debug. Playwright affords hooks like beforeEach and afterEach to arrange and tear down check environments.

check.beforeEach(async ({ web page }) => {
// Login earlier than every check
await web page.goto('https://your-app.com/login');
await web page.fill('#username', 'user1');
await web page.fill('#password', 'password123');
await web page.click on('button[type="submit"]');
});
check('profile web page masses accurately', async ({ web page }) => {
// Navigate to profile web page after login (already carried out in beforeEach)
await web page.goto('https://your-app.com/profile');
// Assert components on profile web page
await count on(web page).toHaveURL(/profile/);
});

Take Benefit of Playwright’s Tooling

Playwright affords instruments like Playwright Inspector for debugging assessments visually, Hint Viewer for analyzing check failures, and Codegen for producing check code from recorded browser actions.

Use Chaining and Filtering

Locators could be mixed to focus the search on a particular part of the web page.

const product = web page.getByRole('listitem').filter({ hasText: 'Product 2' });

It’s also possible to use filter locators by textual content or by one other locator.

await web page
.getByRole('listitem')
.filter({ hasText: 'Product 2' })
.getByRole('button', { identify: 'Add to cart' })
.click on();

Conclusion 

Playwright affords a strong and versatile framework for check automation, making it a worthwhile device for builders and testers alike. Its means to deal with a number of browsers, present cross-platform help, and supply wealthy APIs for interplay and validation makes it stand out within the check automation panorama. By following the step-by-step information, customers can leverage Playwright’s capabilities to create dependable, environment friendly, and scalable automated assessments, finally enhancing the standard and efficiency of their purposes. Embracing Playwright can streamline testing processes, cut back guide effort, and guarantee a extra sturdy and seamless consumer expertise.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version