Sub topic 5
Query and assert on the shadow DOM
This chapter assumes you can already render a component with createElement and attach it to document.body. It also assumes you know basic Jest matchers such as toBe and toContain. Here you will learn how to find elements inside a component's rendered output and assert on them.
Why queries start at the shadow root
Lightning web components render into a shadow root, a separate DOM tree attached to the host element. The tree is hidden from the outside. A query such as document.querySelector('.count') returns null, because the document cannot see inside the component.
Start every query from the shadow root:
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const countEl = element.shadowRoot.querySelector('.count');shadowRoot is available in tests because Jest runs the component with synthetic shadow, which exposes the root for inspection. In a real org, only the component itself can see its own template.
Choosing a query method
Two methods cover most cases.
| Method | Returns | Use it when |
|---|---|---|
| `querySelector(selector)` | The first matching element, or `null` | You expect one element, or only need the first |
| `querySelectorAll(selector)` | A static `NodeList` of all matches | You render a list or need a count |
Prefer selectors that survive refactoring. A class or data- attribute that you added for testing is more stable than a tag name or position in the tree.
Assert on text, attributes, and presence
Once you have an element, assert on the property you care about.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter rendering', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the initial count', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const countEl = element.shadowRoot.querySelector('.count');
expect(countEl).not.toBeNull();
expect(countEl.textContent).toBe('0');
});
it('renders the Add button', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const button = element.shadowRoot.querySelector('button');
expect(button.textContent).toBe('Add');
expect(button.disabled).toBe(false);
});
it('does not render an error message by default', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});
});The three cases show the usual patterns:
- Text: read
textContent. Compare withtoBefor an exact match ortoContainfor a fragment. - Attributes and properties: read
getAttribute('name')for HTML attributes, or a property such asdisabledfor its current state. - Presence or absence: use
not.toBeNull()andtoBeNull(). This is how you testif:trueandlwc:ifblocks.
For lists, check the count and the content:
const items = element.shadowRoot.querySelectorAll('li');
expect(items.length).toBe(3);
expect(Array.from(items).map((li) => li.textContent)).toEqual(['A', 'B', 'C']);Common errors
- Querying
documentinstead ofshadowRoot. The result isnull, and the next line fails withCannot read properties of null. Check the query's starting point first. - Querying before the element is attached. Without
appendChild, the component has not rendered, so the shadow root is empty. - Asserting right after a change. If you set a property or click a button, the DOM updates later. The next chapter covers waiting for it.
- Reaching into a child component's shadow root. A query on your component's shadow root returns the child's host element, not the child's inner markup. Assert on the child's public properties instead.
Exercise
A component's template contains <p class="status">Ready</p>. Your test runs document.body.querySelector('.status') after attaching the element, and the result is null. What is wrong, and how do you fix it?
Show answer
The paragraph lives inside the component's shadow root, which the document cannot query. Use element.shadowRoot.querySelector('.status'), then assert with expect(status.textContent).toBe('Ready').
Exercise
How would you assert that a component renders exactly four <li> elements, and that an .error element is absent?
Show answer
Use expect(element.shadowRoot.querySelectorAll('li').length).toBe(4) and expect(element.shadowRoot.querySelector('.error')).toBeNull().