Test Overview
This test opens a web page with a Shadow DOM element, accesses the shadow root, finds a button inside it, clicks the button, and verifies the button's text changes as expected.
This test opens a web page with a Shadow DOM element, accesses the shadow root, finds a button inside it, clicks the button, and verifies the button's text changes as expected.
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 ShadowDomTest { WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } @Test public void testShadowDomButtonClick() { driver.get("https://example.com/shadowdom"); // Locate shadow host element WebElement shadowHost = driver.findElement(By.cssSelector("#shadow-host")); // Access shadow root using JavaScript JavascriptExecutor js = (JavascriptExecutor) driver; WebElement shadowRoot = (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost); // Find button inside shadow root WebElement shadowButton = shadowRoot.findElement(By.cssSelector("button#shadow-button")); // Click the button shadowButton.click(); // Verify button text changed String buttonText = shadowButton.getText(); assertEquals("Clicked", buttonText, "Button text should change to 'Clicked' after click."); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open, ready to navigate | - | PASS |
| 2 | Navigates to https://example.com/shadowdom | Page with shadow DOM loaded | - | PASS |
| 3 | Finds shadow host element with CSS selector '#shadow-host' | Shadow host element located in DOM | Element '#shadow-host' is present | PASS |
| 4 | Executes JavaScript to get shadow root from shadow host | Shadow root accessed successfully | Shadow root is not null | PASS |
| 5 | Finds button inside shadow root with CSS selector 'button#shadow-button' | Button inside shadow DOM located | Button element is present inside shadow root | PASS |
| 6 | Clicks the shadow DOM button | Button clicked, UI updates accordingly | - | PASS |
| 7 | Gets button text after click | Button text updated to 'Clicked' | Button text equals 'Clicked' | PASS |
| 8 | Test ends and browser closes | Browser closed cleanly | - | PASS |