Whether it be for an advertisement, a call-to-action, or a warning, pops-up are a common way to draw the attention of users.
However, when these alerts and overlays are implemented, it may interfere with testers who are keen on automation. So, how do you use Selenium to close out of a window, or automate testing to interact with a pop-up? We demonstrated the commands for basic pop-ups to make test automation as seamless as possible, without reverting to manual.
There are a few distinct types of alert messages that pop-up with varying user asks.
Simple – A simple alert will usually give minimal information or a warning and only require one, such as clicking an “OK” button to confirm you understand the message.
Prompt– Usually a prompt alert will require the user to input some information such as a name, email, or password before being able to click “OK” to continue.
Confirmation – Confirmation alerts will request permission, which can be answered by clicking “OK” or “Cancel”.
Pop-ups and alerts are usually either Windows-based or web-based. Windows-based alerts are beyond Webdriver capabilities because they’re part of the OS instead of the browser, so you’ll probably need to rely on third-party tools such as Sikuli Script or Robot class.
Using WebDriver for Web-based Pop-ups
WebDriver, on the other hand, does the ability to interact with multiple windows, including alerts, with a method called switchTo. This allows you to switch control to the pop-up while keeping the browser in the background:
popup = @driver.switch_to.alert
From there, these are the simple alert commands for web-based pop-ups:
- To click “Cancel”
- To click “OK”
- To capture the alert message
- To enter information
- To exit
An example of this might be:
require 'selenium-webdriver' require 'rspec/expectations' require 'TimeoutException' include RSpec::Matchers def setup @driver = Selenium::WebDriver.for :firefox end run do @driver.get 'URL' @driver.maximize.window @driver.find_elements(css: 'button').click popup = @driver.switch_to.alert popup.accept textreturned = driver.find_element 'result' print(textreturned.text) assertTrue(textreturned.text, 'You Clicked OK') except TimeoutException: print 'no alert' def teardown end
These commands should take care of any functions you want to perform when automating testing where there are any simple, prompt, or confirmation alert-pop-ups in your browser.
What are the most common challenges that you face testing with Selenium? Tell us in the comments!