How To Work with JavaScript Alerts in Selenium Java, Python, Ruby, C#

Yosuva ArulanthuJava, Python, Ruby, Selenium, Test Automation, TestingLeave a Comment

If your application triggers any JavaScript pop-ups (a.k.a. alerts, dialogs, etc.) then you need to know how to handle them in your Selenium tests.

Built into Selenium is the ability to switch to an alert window and either accept or dismiss it. This way your tests can continue unencumbered by dialog boxes that may feel just out of reach.

Let’s check an example.

Sample code

Java

// filename: JavaScriptAlert.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

public class JavaScriptAlert {
    WebDriver driver;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
    
    @Test
    public void JavaScriptAlertTest() {
        driver.get("http://the-internet.herokuapp.com/javascript_alerts");
        driver.findElement(By.cssSelector(".example li:nth-child(2) button")).click();
        Alert popup = driver.switchTo().alert();
        popup.accept();
        String result = driver.findElement(By.id("result")).getText();
        assertThat(result, is(equalTo("You clicked: Ok")));
    }

}

Python

# filename: javascript_alerts.py
import unittest
from selenium import webdriver


class JavaScriptAlerts(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def tearDown(self):
        self.driver.quit()

    def test_example_1(self):
        driver = self.driver
        driver.get('http://the-internet.herokuapp.com/javascript_alerts')
        driver.find_elements_by_tag_name('button')[1].click()
        popup = driver.switch_to.alert
        popup.accept()
        result = driver.find_element_by_id('result').text
        assert result == 'You clicked: Ok'

if __name__ == "__main__":
    unittest.main()

Ruby

# filename: javascript_alerts.rb

require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers

def setup
  @driver = Selenium::WebDriver.for :firefox
end

def teardown
  @driver.quit
end

def run
  setup
  yield
  teardown
end
run do
  @driver.get 'http://the-internet.herokuapp.com/javascript_alerts'
  @driver.find_elements(css: 'button')[1].click

  popup = @driver.switch_to.alert
  popup.accept

  result = @driver.find_element(id: 'result').text
  expect(result).to eql('You clicked: Ok')
end

C#

// filename: JavaScriptAlerts.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

public class JavaScriptAlerts
{
    IWebDriver Driver;

    [SetUp]
    public void SetUp()
    {
        Driver = new FirefoxDriver();
    }

    [TearDown]
    public void TearDown()
    {
        Driver.Quit();
    }
    [Test]
    public void JavaScriptAlertAppearsAndAccepted()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/javascript_alerts");
        Driver.FindElement(By.CssSelector(".example li:nth-child(2) button")).Click();
        IAlert Popup = Driver.SwitchTo().Alert();
        Popup.Accept();
        string Result = Driver.FindElement(By.Id("result")).Text;
        Assert.That(Result.Equals("You clicked: Ok"));
    }

}

When you run it here is what will happen:

  • Open the browser
  • Load the page
  • Click the second button on the page
  • JavaScript Confirmation Alert appears
  • JavaScript Confirmation Alert is accepted and goes away
  • Assert that the result on the page is what we expect
  • Close the browser

Leave a Reply

Your email address will not be published.