Reach the Input Inside the Shadow Root
intermediate Java 15 minA login test throws NoSuchElementException on an email field that is clearly on screen. The field lives inside a web component's shadow root. Fix it.
The Scenario
The design system team rebuilt the login form as an <app-login> web component with an open shadow root. Nothing changed visually, but the login test, and therefore every test that logs in, now fails:
org.openqa.selenium.NoSuchElementException: no such element:Unable to locate element: {"method":"css selector","selector":"app-login #email"}Someone tried XPath as a workaround and got a different failure. Someone else proposed a JavascriptExecutor call that reads shadowRoot.querySelector(...), which works but bypasses Selenium’s waiting and interactability checks.
Your Task
Use Selenium’s native shadow root support to type the email and password and click Sign in. Make it robust against the component rendering a few hundred milliseconds after the page loads.
What Good Looks Like
- The host is found in the light DOM, then
getShadowRoot()gives aSearchContextto search inside. - Only CSS selectors are used inside the shadow root.
- An explicit wait covers the async render of the inner input.
- No
JavascriptExecutorworkaround. If the root were nested inside another component, you would chaingetShadowRoot()calls one host at a time.
Note: Since Selenium 4.50, Java and .NET also let you anchor relative locators to a shadow root, which helps when the inner elements have no stable attributes.
Your task
A login test throws NoSuchElementException on an email field that is clearly on screen. The field lives inside a web component's shadow root. Fix it.
// HTML under test (abridged):
// <app-login>
// #shadow-root (open)
// <form>
// <input id="email" type="email">
// <input id="password" type="password">
// <button part="submit">Sign in</button>
// </form>
// </app-login>
@Test
void signIn() {
driver.get("https://app.example.com/login");
driver.findElement(By.cssSelector("app-login #email")).sendKeys("qa@example.com");
driver.findElement(By.xpath("//app-login//input[@id='password']")).sendKeys("s3cret");
driver.findElement(By.cssSelector("app-login button")).click();
}
Need Help?
Solution
Try to solve the challenge yourself before revealing the solution.