WebdriverIO - Alerts



WebdriverIO is capable of handling Alerts.

Methods for Alerts

Some methods to work with Alerts are listed below −

browser.isAlertopen()

This method is used to verify if there is an alert in the page. It returns true, if the Alert is present, else returns false

Syntax

The syntax is as follows −

browser.isAlertopen()

browser.getAlertText()

This method is used to get the text present in the Alert.

Syntax

The syntax is as follows −

browser.getAlertText()

browser.acceptAlert()

This method is used to accept an Alert.

Syntax

The syntax is as follows −

browser.acceptAlert()

browser.dismissAlert()

This method is used to dismiss an Alert.

Syntax

The syntax is as follows −

browser.dismissAlert()

In the below image, on clicking Click for JS Alert, an Alert is displayed. Let us obtain the text on the Alert.

Alert

To begin, follow Steps 1 to 5 from the Chapter titled Happy path flow with WebdriverIO which are as follows −

Step 1 − Install NodeJS. The details on how to perform this installation are given in detail in the Chapter titled Getting Started with NodeJS.

Step 2 − Install NPM. The details on how to perform this installation are given in detail in the Chapter titled Installation of NPM.

Step 3 − Install VS Code. The details on how to perform this installation are given in detail in the Chapter titled VS Code Installation.

Step 4 − Create the Configuration file. The details on how to perform this installation are given in detail in the Chapter titled Configuration File generation.

Step 5 − Create a spec file. The details on how to perform this installation are given in the Chapter titled Mocha Installation.

Step 6 − Add the below code within the Mocha spec file created.

// test suite name
describe('Tutorialspoint application', function(){
   //test case
   it('Alerts', function(){    
      // launch url
      browser.url('https://the-internet.herokuapp.com/javascript_alerts')  
      //identify element with xpath then click
      $("//*[text()='Click for JS Prompt']").click()
      //check if Alert is open
      console.log(browser.isAlertOpen())   
      //get Alert Text
      console.log(browser.getAlertText() + ' - Alert Text') 
      //accept Alert
      browser.acceptAlert()
   });
});

Run the Configuration file - wdio.conf.js file with the following command −

npx wdio run wdio.conf.js 

The details on how to create a Configuration file are discussed in detail in the Chapter titled Wdio.conf.js file and Chapter titled Configuration File generation.

The following screen will appear on your computer −

Alert Screen

After the command has been executed successfully, the first true is printed in the console as it is returned by the browser.isAlertOpen() method. Then the Alert text - I am a JS prompt is printed in the console.

Advertisements