0
0
Selenium Pythontesting~10 mins

Why alert handling prevents test failures in Selenium Python - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test opens a webpage that triggers a JavaScript alert. It handles the alert properly to prevent the test from failing due to unhandled alert exceptions.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest

class AlertHandlingTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://the-internet.herokuapp.com/javascript_alerts')

    def test_handle_alert(self):
        driver = self.driver
        # Click the button that triggers alert
        alert_button = driver.find_element(By.XPATH, '//button[text()="Click for JS Alert"]')
        alert_button.click()

        # Wait for alert to be present
        WebDriverWait(driver, 10).until(EC.alert_is_present())

        # Switch to alert and accept it
        alert = driver.switch_to.alert
        alert_text = alert.text
        alert.accept()

        # Verify the result text is updated
        result = driver.find_element(By.ID, 'result').text
        self.assertEqual(alert_text, 'I am a JS Alert')
        self.assertEqual(result, 'You successfully clicked an alert')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser is open and navigated to 'https://the-internet.herokuapp.com/javascript_alerts'-PASS
2Find the button with text 'Click for JS Alert' and click itJavaScript alert is triggered and visible-PASS
3Wait up to 10 seconds for alert to be present using WebDriverWait and expected_conditionsAlert is present and ready to interact-PASS
4Switch to alert, read its text, then accept (close) the alertAlert is closed, page is back to normal stateVerify alert text equals 'I am a JS Alert'PASS
5Find the result element by ID 'result' and verify its textResult text is 'You successfully clicked an alert'Verify result text equals 'You successfully clicked an alert'PASS
6Test ends and browser closesBrowser is closed-PASS
Failure Scenario
Failing Condition: Alert is not handled and test tries to interact with page elements while alert is open
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the test to fail if alert handling is missing?
ATrying to interact with page elements while alert is open
BNot finding the button to click
CBrowser not opening
DIncorrect assertion on result text
Key Result
Always wait for and handle alerts explicitly in Selenium tests to avoid unexpected alert exceptions that cause test failures.