0
0
Selenium Javatesting~10 mins

Executing JavaScript in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page, executes JavaScript to change the page title, and verifies the title was updated correctly.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
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 ExecuteJavaScriptTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void testChangeTitleWithJavaScript() {
        driver.get("https://example.com");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.title = 'New Title';");
        String title = driver.getTitle();
        assertEquals("New Title", title);
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open but no page loaded yet-PASS
2Navigates to https://example.comPage https://example.com is loaded with default title 'Example Domain'-PASS
3Executes JavaScript to change document title to 'New Title'Page title is now 'New Title'-PASS
4Retrieves the page title using driver.getTitle()Page title retrieved as 'New Title'Check if title equals 'New Title'PASS
5Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: JavaScript execution fails or title does not update as expected
Execution Trace Quiz - 3 Questions
Test your understanding
What does the JavaScript code in this test do?
AFills a form input
BChanges the page title to 'New Title'
CClicks a button on the page
DReloads the page
Key Result
Use JavascriptExecutor in Selenium to run JavaScript code directly in the browser when standard WebDriver methods cannot perform the needed action.