Introduction to Playwright Testing
Playwright is a robust and versatile automation library developed by Microsoft. It allows builders and testers to automate internet functions throughout a number of browsers with ease. This information will stroll you thru the fundamentals of utilizing Playwright for take a look at automation, from set up to writing and operating your first assessments. Playwright automation helps Chromium, Firefox, and WebKit, permitting you to check throughout totally different browsers.
On this weblog, we are going to deep dive into the varied options of Playwright and the way we will carry out end-to-end testing with Playwright with detailed examples.
Key Options of Playwright
Beneath are a few of the key options of the Playwright testing device:
- Cross-browser testing: Playwright helps all main browsers out of the field, together with Chromium, Firefox, and WebKit (Safari). This cross-browser help lets you write assessments as soon as and run them throughout a number of browsers with none extra configuration or setup. Playwright ensures constant habits and API throughout all supported browsers, making it simpler to take care of and scale your take a look at suite. Playwright gives built-in help for gadget emulation utilizing browsers like Safari and Chrome.
- Headless and headful modes: Playwright lets you run assessments in headless mode (with out a 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 helpful for debugging, visible inspection, or when you could work together with the browser throughout take a look at execution.
- Computerized ready: Playwright mechanically waits for components to be prepared earlier than interacting with them, decreasing the chance of take a look at flakiness brought on by timing points. It employs clever ready methods, corresponding to ready for community requests to finish or DOM mutations to happen, making certain that assessments are executed reliably and constantly.
- Community interception: Playwright gives highly effective community interception capabilities, permitting you to intercept and modify community requests and responses throughout take a look at execution. This function is beneficial for testing situations involving APIs, mocking responses, simulating community circumstances, or bypassing authentication mechanisms.
- A number of contexts: Playwright lets you create a number of browser contexts inside a single take a look at run, successfully simulating totally different person periods or environments. This function is especially helpful for testing situations involving multi-user interactions, corresponding to chat functions or collaborative instruments.
- Highly effective selectors: Playwright gives a wealthy set of selector methods, together with CSS selectors, XPath, textual content selectors, and extra. It additionally gives superior selector choices, corresponding to dealing with dynamic components, choosing components based mostly on their visibility or accessibility, and choosing components inside iframes and shadow DOMs, that are widespread in fashionable internet functions.
- Screenshot and video seize: Playwright lets you seize screenshots and document movies of your take a look at runs with a single line of code. This function is invaluable for debugging, visible regression testing, and producing visible artifacts for documentation or reporting functions.
- Isolation and parallelism: Playwright gives built-in help for operating assessments in isolation and in parallel. Check isolation ensures that every take a look at run is unbiased and does not intrude with different assessments, stopping state air pollution and bettering take a look at reliability. Parallel take a look at execution can considerably pace up your take a look at suite by using a number of CPU cores or machines, decreasing general take a look at execution time.
Playwright Check Automation Framework
Playwright’s structure is designed to offer 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 internet scraping, automated testing, and different browser automation duties. The structure ensures that assessments and scripts are dependable, environment friendly, and straightforward to take care of.
Credit score: ProgramsBuzz
Key Parts and Processes
1. Shopper Aspect (Automation Scripts)
- Languages supported: Playwright helps JavaScript and TypeScript “natively”, whereas additionally offering “bindings” for Java, Python, and C# for writing automation scripts.
- Check script creation: Customers write take a look at scripts of their most well-liked language. These scripts embody take a look at instances, interplay instructions, and assertions. JSON is commonly used for configuration and information alternate.
2. WebSocket Connection
- Handshake: When a take a look at 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 shopper and the server. That is important for sending instructions to the browser and receiving responses or occasions in real-time.
- Open and chronic connection: The WebSocket connection stays open and chronic all through the session, permitting steady interplay between the take a look at scripts and the browser.
- Connection closure: After take a look at execution, the connection might be closed both by the shopper or the server, marking the tip of the session.
3. Server Aspect (Node.js)
- Node.js server: The server aspect is managed by a Node.js utility, which orchestrates the interplay between the shopper scripts and the browsers.
- Dealing with instructions and occasions: The Node.js server receives instructions from the shopper, processes them, and sends applicable directions to the browsers. It additionally listens for occasions from the browser and relays them again to the shopper.
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 periods, and dealing with community interactions.
- CDP+: The picture additionally mentions CDP+ for browsers like Firefox and WebKit (Safari). Playwright extends help to those browsers through the use of protocols much like CDP, making certain a constant API throughout totally different browsers. Every browser course of (render, browser, community) is managed to simulate person interactions precisely.
How Playwright Check Execution Works
- The shopper (take a look at script) sends directions to the server over the WebSocket connection.
- The server receives these directions and interprets them into instructions that may be understood by the browser cases.
- The server communicates with the browser cases utilizing both CDP or CDP+, relying on the necessities.
- The browser cases execute the instructions, corresponding to navigating to internet pages, interacting with components, or capturing screenshots.
- The outcomes or information from the browser cases are despatched again to the server.
- The server relays the outcomes or information again to the shopper over the WebSocket connection.
Getting Began With Playwright Testing
Beneath are the steps for performing Playwright set up on a Home windows machine:
Step 1: Set up of Node.JS
Playwright is code relies on Node.js, so we want node.js put in in our system, we will 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 are going to create a brand new listing for the playwright challenge 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 challenge with a `bundle.json`
file.
For detailed steps on set up comply with the hyperlink.
Folder Construction of Playwright Automation Instrument
The under screenshots reveal how Playwright creates a default folder hierarchy when it first launches. Beneath is an in depth description of every of those recordsdata and folders that the Playwright framework has.
The picture exhibits the folder construction of a Playwright automation device challenge. This is an evidence of every merchandise within the construction:
.github
: This listing sometimes comprises GitHub-specific recordsdata and configurations, corresponding to GitHub Actions workflows.node_modules
: This listing comprises all of the Node.js modules put in for the challenge. These are the dependencies laid out in bundle.json.assessments
: This listing doubtless comprises the Playwright take a look at recordsdata. These recordsdata outline the assessments that shall be executed utilizing Playwright. We usually create a brand new take a look at file on this folder.tests-examples
: This listing comprises instance take a look at recordsdata or templates that can be utilized as references when writing new assessments..gitignore
: This file specifies which recordsdata and directories ought to be ignored by Git. Generally ignored recordsdata embody node_modules, logs, and construct directories.package-lock.json
: This file is mechanically generated and consists of the precise variations of put in dependencies. It ensures that the challenge is constantly put in throughout totally different environments.bundle.json
: This file comprises metadata in regards to the challenge, together with its dependencies, scripts, and different configurations. It’s essential for managing the challenge with Node.js.playwright.config.js
: This configuration file is restricted to Playwright. It defines settings and choices for operating Playwright assessments, such because the browser settings, take a look at listing, timeout configurations, and many others.
Create First Script in Playwright With Detailed Instance
Earlier than creating the primary script we have to perceive a number 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, corresponding 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');
// Await the web page to load and get the title
const title = await web page.title();
console.log(`Web page title: ${title}`);
await browser.shut();
})();
take a look at()
In Playwright’s take a look at runner (@playwright/take a look at
), the take a look at is used to outline particular person take a look at instances.
Instance
const { take a look at, count on } = require('@playwright/take a look at');
take a look at('primary take a look at', 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 take a look at 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 a lot of assessments.
const { take a look at, count on } = require('@playwright/take a look at');
take a look at.describe('Instance Group', () => {
take a look at('first take a look at', async ({ web page }) => {
await web page.goto('https://instance.com');
const title = await web page.title();
count on(title).toBe('Instance Area');
});
take a look at('second take a look at', 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 take a look at lifecycle. Widespread hooks embody beforeAll
, afterAll
, beforeEach
, and afterEach
.
const { take a look at, count on } = require('@playwright/take a look at');
take a look at.describe('Instance Group with Hooks', () => {
take a look at.beforeAll(async () => {
console.log('Setup earlier than all assessments');
});
take a look at.afterAll(async () => {
console.log('Cleanup in any case assessments');
});
take a look at.beforeEach(async ({ web page }) => {
await web page.goto('https://instance.com');
});
take a look at.afterEach(async ({ web page }) => {
await web page.shut();
});
take a look at('take a look at 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 applying behaves as anticipated. Playwright makes use of apart from assertions. The count on operate takes an precise worth and gives varied matcher strategies to say in opposition to the anticipated worth.
const { take a look at, count on } = require('@playwright/take a look at');
take a look at('assertion take a look at', 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 Check Case
Let’s create a .spec file ‘testGrid.spec.js’ beneath the folder assessments.
We’re masking the situation the place the person 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 mother or father web page, and log off efficiently
Let’s take Playwright testing examples to check end-to-end take a look at situations from login to the positioning 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 mother or father web page, and log off efficiently
Check Situation
- Go to the Web site
- Login into the positioning legitimate credential
- Confirm the person is logged in by various the textual content “dashboard”
- Click on on the ‘codeless’ hyperlink beneath the automation part
- Confirm the textual content “let’s get you started with codeless automation”
- Open the hyperlink ‘actual gadget cloud’ within the new tab after which again to the mother or father web page
- Confirm the textual content “selenium” to ensure the person is again on the mother or father web page
- Logout from the applying
Write a easy Playwright take a look at in file ‘testGrid.spec.js’
which is roofed under performance for the web site.
const { chromium, take a look at, count on } = require("@playwright/test");
take a look at("Testgrid.io Scenario", async ({ browser }) => {
const context = await browser.newContext();
const web page = await context.newPage();
// 1. Go to the Web site https://testgrid.io/
await web page.goto("https://public.testgrid.io/");
// 2. Login into the positioning 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 person 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 Machine Cloud' in a brand new tab after which again to the mother or father 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 ensure the person is again on the mother or father web page
await count on(web page.locator("text=Selenium")).toBeVisible();
// 8. Logout from the applying
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, take a look at, count on } = require("@playwright/test");
Defines a take a look at named "Testgrid.io Scenario"
that makes use of a browser occasion.
Outline a Check Situation:
take a look at("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 Web site: Fill within the login type along with your e-mail and password, click on the sign-in button, and watch for 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 Machine 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 Dad or mum Web page: Examine if the “Selenium” textual content is seen to substantiate the person is again on the mother or father web page.
await count on(web page.locator("text=Selenium")).toBeVisible();
Logout from the Utility: 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 Check Circumstances Regionally
To execute the take a look at instances, you should use Playwright instructions in your terminal. Playwright helps each headed mode (the place you possibly can see the browser window) and headless mode (the place assessments run within the background with out a seen browser window).
Within the part under you will note how we will run playwright take a look at automation in headed and headless mode.
Run Check Circumstances in Headed Mode
In headed mode, you possibly can see take a look at instances are executed within the seen browser window.
- Open your terminal.
- Navigate to the listing the place your Playwright assessments are situated.
- Run the command to execute the assessments in headed mode.
Run the command npx playwright take a look at --ui
or yarn playwright take a look at --ui
as we run the command it should open under display. Click on on the .spec file ‘testGrid.spec.js’
to run the take a look at case in headed mode.
After we click on on testGrid.spec.js, the take a look at case begins executing and at last the take a look at case passes efficiently.
Beneath are the screenshots of the take a look at case execution regionally.
Within the ultimate step, the person is logged out of the applying.
Run Check 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 take a look at case in headless mode npx playwright take a look at
or yarn playwright take a look at
.
Run the command:
‘npx playwright test tests/testGrid.spec.js’
. As you execute this command, the take a look at case begins executing in headless mode.
Within the under screenshot, you possibly can see the take a look at case begins executing in headless mode in Chrome browser as soon as execution is accomplished the take a look at instances go in Chrome.
Run the command ‘npx playwright show-report’
Beneath is the hooked up HTML report.
Playwright Greatest Practices
Beneath are a number of greatest practices of Playwright. By following these greatest practices, you possibly can streamline your testing course of, improve reliability, and preserve code readability:
Leverage Playwright’s Assertions
Playwright gives built-in assertions like toBeVisible
, toHaveText
, and toHaveURL
to validate the applying state after person interactions. This simplifies take a look at logic and improves maintainability.
take a look at('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 on your order!')
});
Leverage Playwright’s Wait Methods
Playwright gives functionalities like waitForSelector
, waitForNavigation
, and count on timeouts to make sure components are loaded and prepared earlier than interplay. This improves take a look at reliability.
Instance
Use the await web page.waitForSelector('#submit-button')
earlier than clicking the submit button.
Preserve Exams Unbiased
Every take a look at ought to operate independently, with its personal information, cookies, and native storage. This makes assessments extra dependable and simpler to debug. Playwright gives hooks like beforeEach
and afterEach
to arrange and tear down take a look at environments.
take a look at.beforeEach(async ({ web page }) => {
// Login earlier than every take a look at
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"]');
});
take a look at('profile web page hundreds appropriately', async ({ web page }) => {
// Navigate to profile web page after login (already accomplished 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 gives instruments like Playwright Inspector for debugging assessments visually, Hint Viewer for analyzing take a look at failures, and Codegen for producing take a look at code from recorded browser actions.
Use Chaining and Filtering
Locators might be mixed to focus the search on a particular part of the web page.
const product = web page.getByRole('listitem').filter({ hasText: 'Product 2' });
You may also use filter locators by textual content or by one other locator.
await web page
.getByRole('listitem')
.filter({ hasText: 'Product 2' })
.getByRole('button', { title: 'Add to cart' })
.click on();
Conclusion
Playwright gives a robust and versatile framework for take a look at automation, making it a beneficial device for builders and testers alike. Its capability to deal with a number of browsers, present cross-platform help, and provide wealthy APIs for interplay and validation makes it stand out within the take a look at 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 functions. Embracing Playwright can streamline testing processes, cut back handbook effort, and guarantee a extra sturdy and seamless person expertise.