Test Overview
This test opens a web page, finds a button, and clicks it using JavaScript execution instead of the normal Selenium click method. It verifies that the click action triggers the expected change on the page.
This test opens a web page, finds a button, and clicks it using JavaScript execution instead of the normal Selenium click method. It verifies that the click action triggers the expected change on the page.
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class ClickViaJavaScriptTest { private WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } @Test public void testClickButtonUsingJavaScript() { driver.get("https://example.com/testpage"); WebElement button = driver.findElement(By.id("js-click-btn")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", button); WebElement message = driver.findElement(By.id("click-message")); String text = message.getText(); assertEquals("Button clicked!", text); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com/testpage | Page loads with a button having id 'js-click-btn' and a hidden message element with id 'click-message' | - | PASS |
| 3 | Finds the button element by id 'js-click-btn' | Button element is located on the page | Element with id 'js-click-btn' is present | PASS |
| 4 | Executes JavaScript to click the button: arguments[0].click() | Button is clicked via JavaScript, triggering page event | - | PASS |
| 5 | Finds the message element by id 'click-message' and reads its text | Message element now visible with text 'Button clicked!' | Text of element 'click-message' equals 'Button clicked!' | PASS |
| 6 | Test ends and browser closes | Browser window closed | - | PASS |