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.
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.
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()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser is open and navigated to 'https://the-internet.herokuapp.com/javascript_alerts' | - | PASS |
| 2 | Find the button with text 'Click for JS Alert' and click it | JavaScript alert is triggered and visible | - | PASS |
| 3 | Wait up to 10 seconds for alert to be present using WebDriverWait and expected_conditions | Alert is present and ready to interact | - | PASS |
| 4 | Switch to alert, read its text, then accept (close) the alert | Alert is closed, page is back to normal state | Verify alert text equals 'I am a JS Alert' | PASS |
| 5 | Find the result element by ID 'result' and verify its text | Result text is 'You successfully clicked an alert' | Verify result text equals 'You successfully clicked an alert' | PASS |
| 6 | Test ends and browser closes | Browser is closed | - | PASS |