In Selenium testing, what is the main reason alert handling helps prevent test failures?
Think about what happens if an alert pops up and the test does not close it.
When an alert appears, Selenium cannot interact with the page until the alert is handled. If not handled, the test throws an exception and fails.
Consider this Python Selenium snippet:
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException
browser = webdriver.Chrome()
browser.get('http://example.com')
try:
alert = browser.switch_to.alert
alert_text = alert.text
alert.accept()
print(f'Alert handled: {alert_text}')
except NoAlertPresentException:
print('No alert to handle')What will this code print if no alert is present on the page?
What does the exception handler do when no alert is found?
The code catches the NoAlertPresentException and prints 'No alert to handle' instead of failing.
You want to verify that an alert contains the text 'Success' before accepting it. Which assertion is correct?
alert = driver.switch_to.alert alert_text = alert.text alert.accept()
Remember that alert text must be read before accepting the alert.
Alert text must be stored before calling accept(), because after accept() the alert no longer exists.
Given this Selenium test snippet:
driver.get('http://example.com')
element = driver.find_element('id', 'submit')
element.click()
text = driver.find_element('id', 'result').text
print(text)The test fails with an UnexpectedAlertPresentException. Why?
Think about what happens if an alert pops up after clicking a button.
If an alert appears, Selenium blocks further commands until the alert is handled. Not handling it causes the exception.
Which approach best integrates alert handling to prevent test failures across multiple Selenium tests?
Think about how to avoid repeating alert handling code and catch unexpected alerts.
A helper method centralizes alert handling, making tests cleaner and more robust against unexpected alerts.