Playwright Tutorial: How to Handle Alerts and Dropdowns

  • Learning Hub
  • Playwright Tutorial: Handling Alerts and Dropdowns

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.

...

Table of Contents

Interaction with alerts in Playwright

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.

  • Simple alert
  • Confirmation alert
  • Prompt alert
  • Modal alert
...

Handling simple alerts in Playwright

In a simple alert, when you press the “Click Me” button, we get an alert box with only the “OK” button, as shown below.

handling simple alerts in playwright

Test scenario:

  • Go to LambdaTest playground’s Alert & Modals page.
  • Press the “Click Me” button, which pops the alert box.
  • Press “OK” in the alert box.

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");
 
GitHub

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.

Handling confirmation alerts in 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.

handling confirmation alerts in playwright

Test scenario:

  • Go to LambdaTest playground’s Alerts & Modal page.
  • Press the “Click Me” button in the JavaScript confirm box, and it will pop the alert box.
  • Press the “Cancel” button.

For that, you have to make basic changes to the previous script.

  • Change the value of locator nth from 0 to 1, where we define the “Click Me” button.
  • To check for “dismiss the alert box”, use the “dismiss” function with an alert.
  • In confirmation alerts, you receive messages when you press “OK” or “Cancel” to test that output message using the“expect” condition.
  • Define message output with the locator function, and to check the test, use the “toContainText” function. Then run the test.
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.

Handling prompt alerts in Playwright

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.

 handling prompt alerts in playwright

Test scenario:

  • Go to LambdaTest playground’s Alert & Modals page.
  • Press “Click Me” in the prompt box.
  • Add “kaushik” to the alert’s inbox.
  • Press “OK” in the alert box.

A prompt alert is similar to confirmation alerts but includes one inbox, so you have to make changes to the previous script for testing.

  • Change the value of locator nth from 1 to 2 where you have defined the “Click Me” button.
  • This time, you need a value you input in the inbox, so you have to use the “defaultValue” function instead of “message” and add some data to the test. Here, for example, we will add “kaushik.”
  • Define id in the page locator for message output, and with the “toContainText” function, add the same data you added with “defaultValue.”
  • Change “dismiss()” to “accept()” because this time, you are testing for the “OK” button.
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:

  • Go to LambdaTest playground’s Bootstrap Modals page.
  • Click on “Launch Modal,” which opens the modal alert box.
  • Press “Save Changes” in the alert box.

You have to add elements and run the click action to perform this test.

handling modal alerts in playwright

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]")

Interaction with dropdowns in Playwright

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
  • Multi select dropdown
  • Advance dropdown

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.

handling single select dropdown in playwright

Test scenario:

  • Go to LambdaTest playground’s select list demo page.
  • Click on the “Please select” dropdown, which will open a list of days.
  • Click on a specific day.

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);
GitHub

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.

dropdown in javascript image

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:

  • With the help of a label, which is the visible text in options.
  •  label: "Tuesday"

  • With the help of value. Value is what, in the option tag, we have given value to all options. It can be the same as a label, but it can also be different, like a series of numbers, alphabets, etc.
  • series of numbers alphabets
  • With the help of an index. An index is an option where you can directly add a number, whichever option you want. For example, here, we need Thursday, so we will go for no. 5.
 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.

Data driven testing framework

Test scenario:

  • Go to LambdaTest playground’s select list demo page.
  • In the multi select list demo, select multiple options.
  • Check the result in the result box.

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.

Data driven testing framework

Test scenario:

  • Go to the LambdaTest playground JQuery dropdown demo page.
  • Click on the dropdown, which opens the list of countries.
  • Select the country from the dropdown list.

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.

Data driven testing framework

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.

Some unique features of Playwright

Creating own function in Playwright

Cool part of Playwright is you can create your own function.

Data driven testing framework
  • For this example, create the function selectCountry.
  • Change hasText from India to countryName.
  • hasText: countryName
  • And you can receive this function argument in the “selectCountry”.
  • async function selectCountry(countryName) 
  • Now you can call our new function repeatedly for different countries, and it will test for all.
  • 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!

slowMo function in Playwright

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:

  • Go to a Playwright config file.
  • Within use, add launchOption.
  • Within launchOption, add slowMo, with time like 1000, 500 (in milliseconds) whatever you want.
 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.

Scale Playwright Testing with LambdaTest cloud

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.

  • Execute the Playwright Parallel testing over 50+ browsers and OS configurations and boost your release speed.
  • Track test execution data with LambdaTest Test Analytics.
  • With HyperExecute, run your test 70% faster than any existing cloud grid.
  • LambdaTest integrates with the best CI/CD tools, such as Jenkins, TeamCity, Travis CI, and many more.
...

Conclusion

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.

LambdaTest

Frequently Asked Questions (FAQs)

Does Selenium use Playwright?

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.

Does Playwright have a UI?

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!!

Next-Gen App & Browser Testing Cloud

Did you find this page helpful?

Helpful

NotHelpful