Run Alerts & Overlay Selenium Tests in Real Devices

Learn to Handle Alerts & Overlay in Selenium and WebdriverIO using real-device cloud seamlessly for accurate test results

Get Started free
Home Guide WebDriverIO Tutorial: Handling Alerts & Overlay in Selenium

WebDriverIO Tutorial: Handling Alerts & Overlay in Selenium

By Priyanka Bhat & Ganesh Hegde, Community Contributors -

WebDriverIO is a NodeJS-based open source automation testing framework that supports both mobile and web application automation. WebDriverIO is managed by the OpenJS foundation. WebDriverIO is feature-rich; it provides a lot of features to users, such as extensible, a lot of in-built reporters, web application testing support, mobile application support, etc. WebDriverIO uses Selenium Webdriver and Chrome DevTools Protocol under the hood.

You can automate almost all features of your web application using WebDriverIO. The complicated scenarios, such as browser pop-ups and overlays, also can be automated using WebDriverIO.

What is the Alert Popup in a Web Application?

The alert boxes are typically invoked by JavaScript; these are system dialogs displayed to the user. The system dialog is not part of the web page that is being shown in the browser, and it doesn’t contain any HTML or CSS codes behind it. The appearance depends on the current browser and operating system. These types of popups are also known as JavaScript popup boxes. As the system dialogs are native to the browser and operating system, unlike other web page elements, you cannot inspect and write the automation code.

Types of alerts pop-ups

  • Alert box: Alert box displays only text with the OK button
  • Confirmation box: The confirmation box displays text with two buttons; the user can either click on OK or CANCEL
  • Prompt Box: The Prompt box provides the input area where the user can enter the required details and click on either OK or Cancel

What is an Overlay Pop-up in a Web Application?

Unlike Alert popups, the Overlays are not native to the browser or operating system. The overlays are typically designed using front-end frameworks such as materialUI, bootstrap, etc.

The Overlays are also called modal pop-ups; since this originated from the application that is running on the browser, the modal popup or overlays can be inspected using the browser inspect tool and automated in a usual way.

How to Handle Alerts in WebDriverIO?

As discussed before, there are three types of pop-ups; the Alert popup is one of them; alert popup automation needs a special mechanism to handle, as they originated from a browser or system. The WebDriverIO provides special commands or functions to handle these alert popups.

Handling Alert box in WebDriverIO

Note: As a prerequisite install WebDriverIO.

The alert box contains text and one button. The alert box can be triggered using JavaScript

Example:

alert(“I am an alert box!”);

The Typical Alert pop-up can be seen below.

1 3

The WebDriverIO provides special commands/functions to handle the Alert pop up

List of available functions/commands to handle the alert popup in WebDriverIO

  • acceptAlert(): This function simulates the OK button click on the alert box
  • getAlertText(): This function returns the text of alert box (Ex: I am an alert box)
  • isAlertOpen(): This function returns the boolean value. Returns true if the alert is displayed, false otherwise.

Example code snippet for handling alert popup in WebDriverIO


//alert-popup.js

describe(‘Alert popup demo’, () => {

  it(‘should accept the alert’, async () => {

    await browser.url(`https://www.w3schools.com/js/tryit.asp?filename=tryjs_alert`);

    await browser.pause(3000);

    let frame = await browser.$(‘#iframeResult’);

    await browser.switchToFrame(frame);

    await $(“button=Try it”).click(); //triggers the alert popup

    await browser.pause(3000);

       const isAlertOpen = await browser.isAlertOpen(); //get the status of alert open or not

    if (isAlertOpen) {

      const alertText = await browser.getAlertText(); //get the alert text

      console.log(“The alert text is: “,alertText) //logs the text to console

      await browser.acceptAlert(); //accepts the alert popup

    }

  });

});


Let’s understand the above code snippet
  • await $(“button=Try it”).click(): The click() command triggers the alert box
  • browser.isAlertOpen(): This method returns the if the alert popup is present on the browser or not
  • await browser.getAlertText(): The getAlertText() captures the alert box text and later we are logging the text message to console using console.log
  • browser.acceptAlert(): The acceptAlert() method simulates the click OK or in short it accepts the alert.

Execution flow:

  1. The test first navigates to https://www.w3schools.com/js/tryit.asp?filename=tryjs_alert
  2. Clicks on the Try it buttons, in turn, trigger the Alert popup
  3. Outputs the alert text to console
  4. Accepts the alert

The above Webdriver alert popup demo test can be executed using the WebDriverIO run command syntax:


npx wdio wdio.conf.js –spec <path_to_spec_file>


The console log output will be shown below

2 3

Handling Confirm Popup Alert in WebDriverIO

The confirm popup typically contains two buttons OK and CANCEL, This can be used to get the user confirmation.  The confirm box can be triggered using JavaScript with confirm() method.

Example:


confirm(“Press a button!”) 

A typically confirm popup can be seen below.

3 2

WebDriverIO users can simulate the popup actions such as clicking on OK or CANCEL.

The WebDriverIO provides the below functions to handle the confirm popup.

All the functions which are available in the alert popup are available; in addition to that, the WebDriverIO provides another function dismissAlert() to simulate the CANCEL button functionality.

List of available functions/commands to handle confirm popup in WebDriverIO

  • isAlertOpen(): This function returns the boolean value. Returns true if confirm popup is displayed, false otherwise.
  • getAlertText(): This function returns the text of confirm alert box (Ex: Press a button)
  • acceptAlert(): This function simulates the OK button click.
  • dismissAlert(): This function or command simulates the CANCEL button click on the confirm box

Example code snippet to handle the confirm popup in WebDriverIO


//confirm-popup.js

describe(‘Confirm popup demo’, () => {

  it(‘should click on cancel button’, async () => {

    await browser.url(`https://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm`);

    await browser.pause(10000);

    let frame = await browser.$(‘#iframeResult’);

    await browser.switchToFrame(frame);

    await $(“button=Try it”).click(); //triggers the confirm popup box

    await browser.pause(10000);

    //returns the status if confirm box opened or not

    const isAlertOpen = await browser.isAlertOpen(); 

    if (isAlertOpen) {

     const confirmMessage = await browser.getAlertText(); //returns the confirm box text

     console.log(‘The confirm message is: ‘, confirmMessage) //logs the text

      //Simulates the Cancel button

      await browser.dismissAlert();

      //Simulates the OK button

      // await browser.acceptAlert();

    }

  });

});

Let’s understand the above code

  • $(“button=Try it”).click(): This line of code triggers the confirm popup box
  • browser.isAlertOpen(): This command checks if the alert is opened or not
  • browser.getAlertText(): This returns the confirm popup alert text, the returned text is later logged as a console log.
  • browser.dismissAlert(): This command simulates the CANCEL button click on confirm popup.

Note: If you want to use the OK button click, you can use the await browser.acceptAlert(); as shown in commented code in the above example.

Let’s understand the execution flow

  1. The test first navigates to the URL https://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm
  2. Then clicks the Try it button, which triggers the confirm popup box
  3. The status of confirm popup box will be checked using isAlertOpen()
  4. If the confirm box is visible, the text will be captured and logged into the console
  5. If the confirm box is visible in the browser, then the Cancel button will be clicked.

You can execute the above confirm prompt box example using the WebDriverIO execute command syntax:

npx wdio wdio.conf.js –spec  <path_to_spec.js> 

The command line output will be shown below

4

Handling the Prompt box in WebDriverIO 

The prompt box is also known as the input alert box, the prompt box typically contains one user input field, the OK and CANCEL buttons. The prompt box is used for capturing user input. When the prompt box is displayed on the browser, either the user can choose to enter the input field and click on the OK button or can click on the CANCEL button.

The prompt() function in javascript triggers the prompt popup on the browser.

Example to trigger the prompt box in JavaScript: 

let person = prompt(“Please enter your name:”); 

The prompt box can be seen below.

5 2The WebDriverIO provides the special command to type the text in the prompt box. The sendAlertText() function can be used to enter the text in the prompt box.

All the functions/commands which are available for the confirm box are still available to the prompt popup. The additional sendAlertText() function is provided to enter the text in the prompt pop-up.

List of available functions/commands to handle prompt popup in WebDriverIO

  • isAlertOpen(): This function returns the boolean value. Returns true if the prompt popup is displayed, false otherwise.
  • getAlertText(): This function returns the text of the prompt alert box (Ex: Please enter your name:)
  • acceptAlert(): This function simulates the OK button click.
  • dismissAlert(): This function or command simulates the CANCEL button click on the confirm box
  • sendAlertText(): This function sets the input field text to given string

Example code to handle the prompt popup in WebDriverIO


describe(‘Prompt popup’, () => {

  it(‘should type in prompt and accept’, async () => {

    await browser.url(`https://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt`);

    await browser.pause(7000);

    let frame = await browser.$(‘#iframeResult’);

    await browser.switchToFrame(frame);

    await $(“button=Try it”).click(); //triggers prompt box

    await browser.pause(7000);

    const isPromptOpen = await browser.isAlertOpen(); // checks if prompt is open

    if (isPromptOpen) {

      await browser.sendAlertText(“BrowserStack”); // types the text BrowserStack

      await browser.pause(1000);

      const promptboxText = await browser.getAlertText();//returns the text of prompt box

      await console.log(“The prompt box text is: “, promptboxText); //logs the text

      //Click on OK in prompt box

      await browser.acceptAlert(); //accepts the prompt box

    }

    await browser.pause(7000);

    //To dismiss the prompt box 

    //await browser.dismissAlert();

  });

});

Let’s understand the above code,

  • browser.isAlertOpen(): Checks if the prompt is open or not
  • browser.sendAlertText(“BrowserStack”): Types the text in prompt box input field
  • browser.getAlertText(): returns the prompt box text, and later it will be logged to the console output
  • browser.acceptAlert(): Accepts the prompt box, same as clicking the OK button.

Execution flow

  1. Navigates to the  URL https://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt
  2. Clicks on the Try it button, which in turn shows the prompt popup box
  3. Checks if the prompt box is open
  4. If the prompt box is open, then set the input field to BrowserStack
  5. Gets the prompt box text and logs to the console.
  6. Accepts the prompt box

You can execute the above confirm prompt box example using the WebDriverIO execute command syntax:

npx wdio wdio.conf.js –spec  <path_to_spec.js>

The console output will be shown below.

6 2

Talk to an Expert

Handling overlay box in WebDriverIO

The overlay box is handled by the application, though for a user, it feels like a popup; it doesn’t originate from the system or browser, so the overlay popup or modal can be inspected using the browser inspector tool and automated.

The typical overlay popup looks like below.

7 2

Just like any other HTML element, the modal can be inspected, and get the text, close the popup or click the X button.

Example code to handle the overlay popup in WebDriverIO


describe(‘Overlay pop up’, () => {

  it(‘should close the overlay pop up’, async () => {

    await browser.url(`https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal&stacked=h`);

    await browser.pause(3000);

    let frame = await browser.$(‘#iframeResult’);

    await browser.switchToFrame(frame);

    await $(“button=Open Modal”).click(); //opens the modal popup

    await browser.pause(1000);

    await $(“button.close”).click(); //closes the modal popup

    await browser.pause(7000);

  });

});

Let’s understand the code

  •  $(“button=Open Modal”).click(): This code opens the overlay modal popup
  • $(“button.close”).click(): This line of code closes the modal popup

As you can see from the above code, there is no special mechanism required to handle the modal pop-up in WebDriverIO

BrowserStack Automate Banner

Execution flow

  1. Navigates to the URL https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_modal&stacked=h
  2. Clicks on the Open Modal button
  3. Clicks on the Modal close (X) button

overlay

How to Perform Cross Browser Testing on BrowserStack

  • Install the @wdio/browserstack-service with the command

npm install @wdio/browserstack-service 

  • Login to the Browserstack account and copy the Access Key and Username
  • Open the wdio.conf.js configure the key and user

   user: “<user_name>”,

    key: “<access_key>”

Example:


exports.config = {

    user: “gasomeooemekj”,

    key: “asdfjsadfiekkdl”,

 

  
  • Configures services option

    services: [

        [‘browserstack’, {

            browserstackLocal: true

        }]

    ],

  • Configure the capabilities as shown below

 capabilities: [{

        maxInstances: 5,

        browserName: ‘chrome’,

            ‘bstack:options’: {

                buildName: ‘browserstack-webdriverIO-build’,

                os: ‘OS X’,

 

              },

        acceptInsecureCerts: true,

        excludeDriverLogs: [‘*’], // pass ‘*’ to exclude all driver session logs

        // excludeDriverLogs: [‘bugreport’, ‘server’],

    }],

Putting everything together


//wdio.conf.js

exports.config = {

    user: “lorem_ipsum”,

    key: “lorem_ipsum”,

    services: [

        [‘browserstack’, {

            browserstackLocal: true

        }]

    ],

    capabilities: [{

        maxInstances: 5,

        browserName: ‘chrome’,

 

            ‘bstack:options’: {

                buildName: ‘browserstack-webdriverIO-build’,

                os: ‘OS X’,

 

              },

        acceptInsecureCerts: true,

        excludeDriverLogs: [‘*’], 

 

    }],

    specs: [

        ‘./test/specs/**/*.js’

    ],

    exclude: [

    ],

    maxInstances: 10,

    logLevel: ‘silent’,

    bail: 0,

    baseUrl: ‘https://www.browserstack.com’,

 

    waitforTimeout: 10000,

    connectionRetryTimeout: 120000,

    connectionRetryCount: 3,

    framework: ‘mocha’,

    reporters: [‘spec’],

    mochaOpts: {

        ui: ‘bdd’,

        timeout: 60000

    },

}

  • Execute test with WebDriverIO execution command,

npx wdio wdio.conf.js –spec <path_to_spec.js>

 

The WebDriverIO supports all major browsers and operating systems. Cross browser testing is easy in WebDriverIO compared with any other automation framework. However, cross browser and cross platform testing need a stable environment and infrastructure. Setting up infrastructure and maintaining them is the most difficult job and involves cost. The cloud-based testing platform such as BrowserStack, makes it easy by providing thousands of real devices. A user only needs to change the configuration file options, and the existing test cases can be run on various without making any changes.  The cross-browser testing increases the confidence of stakeholders and ensures minimal bugs in production.

Try BrowserStack now!

Tags
WebdriverIO

Featured Articles

WebdriverIO Tutorial: Getting started with Test Automation using Selenium and Appium

Cross Browser Testing using WebdriverIO

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers