Test Overview
This test opens a webpage, scrolls to a specific element using JavaScript, and verifies that the element is visible on the screen.
This test opens a webpage, scrolls to a specific element using JavaScript, and verifies that the element is visible on the screen.
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(); } } }
| 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/longpage | Page with long content is loaded in browser | - | PASS |
| 3 | Finds element with id 'target-element' | Element located in the DOM | Element is found without exception | PASS |
| 4 | Executes JavaScript to scroll element into view | Page scrolls so that the target element is visible in viewport | - | PASS |
| 5 | Checks if the target element is in viewport | Element is in viewport | assertTrue(isInViewport) verifies element is in viewport | PASS |
| 6 | Test ends and browser closes | Browser window is closed | - | PASS |