DOM Inspection Tests Are Subject to Change
The content and structure of HTML, CSS, and the DOM in Lightning Experience can change at any time and can’t be considered a stable API. UI tests that use tools like Selenium WebDriver to reach into component internals require your ongoing maintenance.
Salesforce has never guaranteed backward-compatible HTML, CSS, or DOM. We’re calling out the fragility of these tests due to changes as Lightning Experience continues to evolve with modern web standards. We understand the value that you gain from automated UI testing, and the maintenance burden this puts on you.
Lightning web components are based on the Web Components standard. This standard includes Shadow DOM, which hides a component's markup, style, and behavior from other components. This encapsulation poses challenges for UI tests, especially tests that rely on globally searching the DOM or reaching into the internals of custom elements.
shadowRoot property encapsulates an element's DOM subtree. This
shadowRoot is represented as a
DocumentFragment in the DOM. Elements inside this DOM subtree are not available by traditional DOM querying methods. Elements that are rendered by Lightning web components contain this new
shadowRoot property, and these elements are hidden from normal DOM queries.
We recommend using Jest to unit test individual Lightning web components.
Use UI testing tools like Selenium WebDriver only for end-to-end testing.
To write unit tests for Lightning web components, use sfdx-lwc-jest.
In a Jest test context, code can use the
shadowRoot property of the element under test to access the shadow tree. The
shadowRoot property encapsulates an element’s shadow tree.
This code accesses the
<div> in the shadow tree of the
<lightning-lwc-parent> component in the Example section.
For end-to-end UI tests, adapt your existing tests for Shadow DOM use. Adapting your tests varies by tool, and strategies are rapidly evolving. This article is a good example for Selenium WebDriver.
As the article discusses, global queries via
The article has a screenshot that shows DOM elements in Chrome Developer Tools. The screenshot shows a
#shadow-root document fragment, which is the top node of a component’s shadow tree. If you look at a Lightning web component in Chrome Developer Tools, you don’t see the
#shadow-root because LWC uses a shadow DOM polyfill. Salesforce supports some browsers that don’t implement the Shadow DOM web standard. The polyfill provides a shadow DOM in these browsers. To find Lightning web components on the page, look for element names that contain a hyphen. Select the element and run
$0.shadowRoot in the Console. A Lightning web component returns