0
0
Selenium Javatesting~10 mins

Scrolling into view in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, scrolls to a specific element using JavaScript, and verifies that the element is visible on the screen.

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.assertTrue;

public class ScrollIntoViewTest {
    private WebDriver driver;

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

    @Test
    public void testScrollIntoView() {
        driver.get("https://example.com/longpage");
        WebElement targetElement = driver.findElement(By.id("target-element"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", targetElement);
        boolean isInViewport = (Boolean) ((JavascriptExecutor) driver).executeScript(
            "var rect = arguments[0].getBoundingClientRect(); " +
            "return rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight);",
            targetElement);
        assertTrue(isInViewport, "Target element should be in viewport after scrolling into view.");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigates to https://example.com/longpagePage with long content is loaded in browser-PASS
3Finds element with id 'target-element'Element located in the DOMElement is found without exceptionPASS
4Executes JavaScript to scroll element into viewPage scrolls so that the target element is visible in viewport-PASS
5Checks if the target element is in viewportElement is in viewportassertTrue(isInViewport) verifies element is in viewportPASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: Element with id 'target-element' is not found or not in viewport after scrolling
Execution Trace Quiz - 3 Questions
Test your understanding
What Selenium method is used to scroll the element into view?
AexecuteScript with scrollIntoView JavaScript
Bdriver.scrollToElement()
Cdriver.scrollBy()
Delement.scroll()
Key Result
Use JavaScript's scrollIntoView to bring elements into the visible area before interacting, ensuring reliable element viewport visibility checks.