Tutorial 8 – Handle JavaScript Alerts using Selenide
What you will Learn:
Handle js alert (example#1)
Handle js alert (example#2)
Code snippet
Handle js alert (example#1)
Launch https://the-internet.herokuapp.com/javascript_alerts
We can see JS buttons. When we click ‘Click for JS Confirm’, we see javascript alert popup having OK/Cancel buttons
Inspect ‘Click for JS Confirm’
Launch the site and click the button
Save and execute
Let us now switch to alert and perform the getText() operation to fetch the text seen on the popup
Save and execute
Let us now assert the text on the alert popup and click the OK button (accepting the alert)
Save and execute.
Notice that the alert popup is closed and assertion passes
Handle js alert (example#2)
Let us see another example. Launch
http://tizag.com/javascriptT/javascriptalert.php
Click the alert button, a popup gets displayed
Inspect the alert button
Modify the script
Save and execute.
You would notice that the popup gets closed (viz accepted).
Code snippet
package w2a.selenide;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.codeborne.selenide.CollectionCondition;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.WebDriverRunner;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
public class FirstSelenideTest {
@Test
public void searchTest() throws InterruptedException {
//open("https://the-internet.herokuapp.com/javascript_alerts");
open("http://tizag.com/javascriptT/javascriptalert.php");
$(By.xpath("//tbody/tr[1]/td[1]/div[4]/form[1]/input[1]")).click();
//$(By.tagName("button")).click();
Alert jsal = switchTo().alert();
/*
String jsal_text = jsal.getText();
System.out.println(jsal_text);
Assert.assertEquals(jsal_text, "I am a JS Alert");
*/
jsal.accept();
Thread.sleep(5000);
}
}
Thank you for reading!