Outline

In this post we will learn how to work with alerts while we are doing web automation with selenium webdriver.

Audience

This post is designed for SW test professionals who have some information about selenium web automation. At the end of this tutorial, you will know how to work with alerts.

Prerequisites

Nice to have: Before starting to read this post it is better to read previous selenium tutorials.

Working with Alerts

Generally speaking, modern web sites do not contain alerts too much. However, when we faced with an alert, we should know how to handle it. In JavaScript code alert(“Hello World!”) is an example of an alert and we can handle alerts by switching to alert window and then we call webdriver alert API’s interrogation and manipulation methods. These are:

  • .getText() – Gets the text of an alert
  • .sendKeys(String) – Send string to the alert
  • .accept() – Clicks the “Ok” button of the alert
  • .dismiss() – Clicks the “Cancel” button of the alert
Note: Alert is an entirely different window so before using above methods we have to switch to alert window by using switchTo() method.

Now it is time to do exercises 🙂

1-) Alert Example

Test site: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert

Test Scenario:

  • Navigate to above link.
  • Click the “Try it” button
  • Capture the alert’s text
  • Accept the alert (In other words, Click OK button.)

CSS of “Try it” Button: html>body>button

Test Code:

2-) Confirm Example

Test site: http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm

Test Scenario-1:

  • Navigate to above link.
  • Click the “Try it” button
  • Click OK button. (Accept it)
  • Check expected text as “You pressed OK!”

Test Scenario-2:

  • Navigate to above link.
  • Click the “Try it” button
  • Click Cancel button. (Dismiss it)
  • Check expected text as “You pressed Cancel!”

CSS of “Try it” button: html>body>button

CSS of expected text: #demo

Test Code:

3-) Prompt Example

Test site: http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm

Test Scenario:

  • Navigate to above link.
  • Click the “Try it” button
  • Write “SW Test Academy” to the alert text box.
  • Click OK button. (Accept it)
  • Check expected text as “Hello SW Test Academy! How are you today?”

CSS of “Try it” button: html>body>button

CSS of expected text: #demo

Test Code:

Summary

  • You learnt how to work with Alerts, Confirm, and Prompt windows.