Selenium C# Tutorial: Working with JavaScript Alerts (C#)

Updated: Jan 18

I think that it will be a fair statement that Web developers use JavaScript alerts to inform users about accepting an input value, validation errors warning, etc. As part of the testing process, you will need to verify that the customer is shown correct alerts while working with the functionality under tests. It would also be required to handle alerts while performing an E2E workflow. The Selenium WebDriver provides an Alert class for working with JavaScript alerts.

This tutorial will handle a simple alert box using Selenium WebDriver's Alert class. A simple alert box is usually used to notify the customer of errors, warnings, and success. When an alert box pops up, the customer will usually have two options to select the “OK” button to proceed and the “Cancel” button to stop the current execution, as shown in the example below:

When we create tests, we will encounter situations where we will need to validate that the JavaScript alerts are triggered at the correct time or that the user receives the relevant alert based on the functionality he used.



The OpenQA.Selenium.IAlert package. Alert interface gives us the following methods to deal with the alert:

  • .Accept() To accept the alert

  • .Dismiss() To dismiss the alert

  • .Text To get the text of the alert

  • .SendKeys() To write some text to the alert

Two important notes that are worth mentioning before diving into the code examples:

  1. Before starting working with the JS alert window, we need to use the driver.SwitchTo().Alert().

  2. Common Exception in this Alert Handling is NoAlertPresentException:


Handling Different Alert Types Using Selenium C#

This tutorial will examine the different alert types, such as simple, confirmation, and prompt alerts. The test URL which contains these different alert types are http://the-internet.herokuapp.com/javascript_alerts.



Simple Alert

Simple JS alerts have a single 'OK' button on them. Their primary use is to display some information to the user.

Code:

[TestMethod]
public void HandlingSimpleJavaScriptAlert()
{
String expectedButtonName = "Click for JS Alert";
String simpleJavaScriptAlert = ".example > ul:nth-child(3) > li:nth-child(1) > button:nth-child(1)";
string AlertText = "I am a JS Alert";

//Validate button is available 
IWebElement alertButton = Driver_Wait.Until(ExpectedConditions.ElementExists(By.CssSelector(simpleJavaScriptAlert)));           
Assert.AreEqual(expectedButtonName, alertButton.Text);

//Log
Console.WriteLine(" (1) - Alert button {0} is available", alertButton.Text);

//Click() method is performed to load the alert window.
alertButton.Click();

//Switch the focus of 'driver' to the Alert
var simpleAlertWindow = driver.SwitchTo().Alert();

//Validate the alert text prior to accept the alert
Assert.AreEqual(AlertText, simpleAlertWindow.Text);

//Log
Console.WriteLine(" (2) - Alert button {0} is available", simpleAlertWindow.Text);

//'.Accept()' is used to accept the alert
simpleAlertWindow.Accept();            
}

Result:



Confirmation Alert

This alert comes with a user option to ‘Accept’ or ‘dismiss’ the alert. To accept the alert, you can use IAlert.Accept() and to dismiss, you can use the IAlert.Dismiss().

Code:


Example 1: Using the IAlert.Accept() method


[TestMethod]
public void HandlingConfirmationAlert_Dismiss()
{
String CSSButtonName = "button[onclick='jsConfirm()']";
var expectedAlertText = "Click for JS Confirm";

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

try
{
/Identify and click on the "Click for JS Confirm" button 
IWebElement JSConfirmButton = wait.Until(ExpectedConditions.ElementExists(By.CssSelector(CSSButtonName)));

Assert.AreEqual(expectedAlertText, JSConfirmButton.Text);                

//Log
Console.WriteLine(" (1) - Alert button {0} is available", JSConfirmButton.Text);
            
JSConfirmButton.Click();

//Switch the control of 'driver' to the Alert from main window
var confirm_win = driver.SwitchTo().Alert();

//Log
Console.WriteLine(" (1) - Alert button {0} is available", confirm_win.Text);

// Click Cancel button, by calling Dismiss() method of Alert Class
confirm_win.Dismiss();
 }
catch (NoAlertPresentException ex)
{
 Console.WriteLine("Test fail with error: {0}", ex.Message);                
}
}


Result:

Example 2: Using the IAlert.Dismiss(). method


[TestMethod]
public void HandlingConfirmationAlert_Accept()
{
String CSSButtonName = "button[onclick='jsConfirm()']";
var expectedAlertText = "Click for JS Confirm";

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

try
{
//Identify and click on the "Click for JS Confirm" button 
IWebElement JSConfirmButton = wait.Until(ExpectedConditions.ElementExists(By.CssSelector(CSSButtonName)));

Assert.AreEqual(expectedAlertText, JSConfirmButton.Text);

//Log
Console.WriteLine(" (1) - Alert button {0} is available", JSConfirmButton.Text);

JSConfirmButton.Click();

//Switch the control of 'driver' to the Alert from main window
var confirm_win = driver.SwitchTo().Alert();

//Log
Console.WriteLine(" (1) - Alert button {0} is available", confirm_win.Text);

// Click Cancel button, by calling Dismiss() method of Alert Class
confirm_win.Accept();
}
catch (NoAlertPresentException ex)
{
Console.WriteLine("Test fail with error: {0}", ex.Message);
}

var actualResult = driver.FindElement(By.Id("result"));
//Validate Result Text
Assert.AreEqual("You clicked: Ok", actualResult.Text);            
}

Result:

Send Text to a window and approve it

in this code sample, we will add a string to an alert window, accept it and then validate its results.


Result:



348 views0 comments