0
0
Selenium Javatesting~10 mins

Clicking via JavaScript in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit with Selenium WebDriver
Selenium Java
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);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigates to https://example.com/testpagePage loads with a button having id 'js-click-btn' and a hidden message element with id 'click-message'-PASS
3Finds the button element by id 'js-click-btn'Button element is located on the pageElement with id 'js-click-btn' is presentPASS
4Executes JavaScript to click the button: arguments[0].click()Button is clicked via JavaScript, triggering page event-PASS
5Finds the message element by id 'click-message' and reads its textMessage element now visible with text 'Button clicked!'Text of element 'click-message' equals 'Button clicked!'PASS
6Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: The button with id 'js-click-btn' is not found or JavaScript click does not trigger the expected message change
Execution Trace Quiz - 3 Questions
Test your understanding
Which Selenium method is used to perform the click in this test?
AJavascriptExecutor.executeScript with arguments[0].click()
BWebElement.click()
CActions.moveToElement().click()
DsendKeys(Keys.ENTER)
Key Result
Using JavaScript to click elements can help when normal Selenium click fails due to overlays or hidden elements, but always verify the click triggers the expected page behavior.