CHAPTERS
OVERVIEW
Released in 2020 by Microsoft, Playwright has become an enormous player in the automation testing field domain. In a span of a couple of years, Playwright has gained popularity among testers.As per the State of JS study, Playwright consistently managed to retain 93% of users.
The reason is simple: Playwright’s futuristic features, such as automating scenarios for multiple pages and an automation driver not constrained by in-page JavaScript execution. Such unique automation capabilities make Playwright a better option than any existing frameworks.
In this Playwright testing tutorial, you will get your hands on automating alerts and dropdowns and other functions, such as slowmo, to help you debug superfast tests and create your own functions.
During website interaction, many actions require special permission or attention from users. That's why site alerts are essential to test. Let's understand how to test the alert box using Playwright.
We will use Selenium playground to perform tests on the LambdaTest platform.
LambdaTest is a continuous quality cloud to perform manual and automated testing of websites and mobile applications. It provides a cloud grid for Playwright testing, which you can accelerate by 10X with parallel test execution.
LambdaTest playground provides different test demo pages. Here we will test four different types of alerts.
In a simple alert, when you press the “Click Me” button, we get an alert box with only the “OK” button, as shown below.
Test scenario:
One important thing here is when that alert box pops up, we cannot right-click or inspect. Usually, to interact with any element, we will need locator and web elements. Here, we will find and define elements in a JavaScript way.
Step 1: Define the page with the “goto” command.
import { expect, test } from "@Playwright/test";
test("handling alerts", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo");
Step 2: Define the element with the help of the locator command. But on this page, there are three “Click Me” buttons, and the locator command cannot find more than one element. It is called strict default behavior.
await page.locator("button:has-text('Click Me')").nth(0).click();
When the same locator value has multiple elements, we use the nth locator command, which disables the strict property of the locator command, and now it can find multiple elements. Here we will give it the number “0”.
Step 3: When you press “Click Me,” you get an alert message, so before clicking action, you first have to handle the alert.
For that, you have to activate the “event listener” so it will get active when you click on the button. It's quite the reverse process.
Step 4: Use the accept function to accept the alert. It will require “await” functions for accepting because you have to handle the promises here.
Step 5: To check and print the message in the alert box, use a function called a message to read text from the alert box in the reporter's standard output.
page.on("dialog", async (alert) => {
const text = alert.message();
console.log(text);;
await alert.accept();
})
Run the test.
Also, here is a comprehensive tutorial where you can learn about alerts and dialogs and how to handle them with Playwright.
In the confirmation box, we get two buttons, “OK” and “Cancel,” and when we accept an alert, we get OK, and when we dismiss, we receive a cancel message. So we have to write the common condition for that.
Test scenario:
For that, you have to make basic changes to the previous script.
page.on("dialog", async (alert) => {
const text = alert.message();
console.log(text);;
await alert.dismiss();
})
await page.locator("button:has-text('Click Me')").nth(0).click();
expect(page.locator("id=confirm-demo")).toContainText("Cancel!")
In our previous tutorial on handling inputs and buttons in Playwright, we used toHaveText, which checks the entire text; likewise, toContainText is used to check text partially. Here we want to check that when we dismiss the alert box, we must get “Cancel!” in our message.
A prompt alert is when you can pass some data in the alert box and have the “OK” and “Cancel” buttons. When you press “OK”, you will get that data in the output.
Test scenario:
A prompt alert is similar to confirmation alerts but includes one inbox, so you have to make changes to the previous script for testing.
page.on("dialog", async (alert) => {
const text = alert.defaultvalue(kaushik);
console.log(text);;
await alert.accept();
})
await page.locator("button:has-text('Click Me')").nth(2).click();
expect(page.locator("id=prompt-demo")).toContainText("'kaushik'");
A modal alert is different from other JavaScript alerts. For modal alerts, you have a bootstrap modal in the Selenium playground. Here you can inspect and find elements of buttons.
Test scenario:
You have to add elements and run the click action to perform this test.
Step 1: Create a new test block and define the page URL.
Step 2: Inspect the element of the “Launch Modal” button and run the click action for it.
Step 3: When you press the button, the alert box opens, and to test for the “Save Changes” button, perform the click action for that button. Now run the test.
test("Modal alert", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/bootstrap-modal-demo")
await page.click("//button[@data-target='#myModal']")
await page.click("(//button[text()='Save Changes'])[1]")
Run Automated Playwright Tests Online. Try LambdaTest Now!
Just imagine that you have an eCommerce website and you have a huge list of categories, but you can’t use dropdowns. Your whole website will be a mess. A drop-down menu is essential for keeping your website well-organized and in order.
The dropdown menu helps users skip scrolling and select the option they want. Now we will write a test script in Playwright for these three types of dropdowns.
Single select dropdown is where you have multiple options and when you have to select one. It's used where you have one possible answer, for example, age, gender, etc.
Test scenario:
Here is the test script for a simple dropdown.
test("handling dropdown", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
await page.selectOption("#select-demo", {
label: "Tuesday"
value: "Friday"
index: 5
})
await page.waitForTimeout(3000);
Before we start the test, let's understand the dropdown in JavaScript. In JavaScript, for dropdown, it has a select tag; there is a list of options, as shown in the screenshot.
Let's start writing a test script for it:
Step 1: Create a new file for the dropdown and create a new test block within it.
Step 2: Define the URL with the help of the goto command.
Step 3: Now define the locator and select it. The Playwright has an individual function named “selectOption”
In this function, you have to add XPath id in string form and, within it, add an option.
There are three different ways to select the option:
label: "Tuesday"
index: 5
Step 4: Since there are only two steps in execution, testing will complete so fast that we cannot see the result in the video. To avoid that, Playwright has the command name “waitForTimeout”.
With it, you can delay timeout and can see results correctly.
await page.waitForTimeout(3000)
Now run the test.
Multi select dropdown is used for selecting multiple options at the same time. For example, selecting hobbies, languages, interests, etc.
Test scenario:
Here is the test script for multi select dropdown.
import { test } from "@playwright/test";
test("handling dropdown", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
await page.selectOption("#select-demo", {
// label: "Tuesday"
// value: "Friday"
index: 5
})
await page.waitForTimeout(3000);
await page.selectOption("#multi-select", [
{
label: "Texas"
}, {
index: 2
}, {
value: "Washington"
}
])
})
Its testing script is similar to a single select with some additions and modifications. You must create an array in the “selectOption” function where you will pass multiple objects.
We used the label, index, and value methods for better understanding, but you can also go with anyone.
jQuery select dropdown is a dropdown with a search box where we can type text and get relevant results. It's used where the list is extensive, so with the help of an inbox, users can find options easily.
Test scenario:
Here is the test script for the JQuery dropdown testing.
test.only("Bootstrap dropdown", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/jquery-dropdown-search-demo");
await selectCountry("India");
await selectCountry("Denmark");
await selectCountry("South Africa");
// await page.waitForTimeout(3000)
async function selectCountry(countryName) {
await page.click("#country+span");
await page.locator("ul#select2-country-results")
.locator("li", {
hasText: countryName
}).click();
}
})
A common way to test the jQuery dropdown is simply writing text in the inbox and finding results, but we will try some cooler or rather Playwright way to execute this test.
Step 1: Define the page URL with the help of the goto command.
Step 2: Perform a click action to open the list. In inspect, you will find the id and add its siblings. So your locator will look like this.
await page.click("#country+span");
Step 3: Once your menu opens, inspect the value for every option where you can see a list in the li tag, and the li tag is within the ul tag.
Your initial locator will be that ul tag, and inside it, pick one more locator which has a li tag.
And then, with the help of the “hasText” command, define the text within that li tag.
async function selectCountry() {
await page.click("#country+span");
await page.locator("ul#select2-country-results")
.locator("li", {
hasText: “india”
}).click();
}
What we did is defined one element, and within that, we defined an inner element, and inside that element, we gave a command to find text.
You can do the same thing in Selenium, but the Playwright locator strategy is unique and easy.
Cool part of Playwright is you can create your own function.
hasText: countryName
async function selectCountry(countryName)
test.only("Bootstrap dropdown", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/jQuery-dropdown-search-demo");
await selectCountry("India");
await selectCountry("Denmark");
await selectCountry("South Africa");
// await page.waitForTimeout(3000)
async function selectCountry(countryName) {
await page.click("#country+span");
await page.locator("ul#select2-country-results")
.locator("li", {
hasText: countryName
}).click();
Have fun with this cool trick!
Sometimes, you might be debugging and want to see the output of the test, but a test runs superfast. To slow it down to see what is happening in real time, Playwright has one function called “slowMo”.
Here is how to use slowMo:
launchOptions: {
slowMo: 1000
},
When you execute the test while adding slowMo, it slows down the process by taking a break of 1 second (or whatever time we include) at every step.
You can leverage the true capabilities of the Playwright test automation framework by running the test on cloud grids like LambdaTest. Cloud testing platforms like LambdaTest allow you to run your Playwright test on 50+ browsers and browser versions such as Chrome, Firefox, Opera, Edge, etc.
So here, we learned about various types of alerts and dropdowns and functions like locator nth, toContainText, selectOption, slowMo, waitForTimeout, etc. Also, useful and unique features like creating functions. We hope those steps and processes have cleared your doubts about handling alerts and dropdowns in Playwright.
If you missed any previous tutorials, here is our tutorial for Playwright automation testing.
Follow the LambdaTest YouTube Channel to stay updated on automation testing like Selenium testing, Appium automation, Cypress testing, and more.
Like Cypress, Playwright is a fully independent solution that is not based on Selenium. It supports all popular browsers and a variety of programming languages, including Python, Java, and JavaScript.
Playwright automatically launches headless browsers. You must use the command line because headless browsers don't show a user interface. Additionally, Playwright may be set up to run a complete (non-headless) version of Microsoft Edge.
Try LambdaTest Now !!
Get 100 minutes of automation test minutes FREE!!
Did you find this page helpful?