Sub topic 5
Query and assert on the shadow DOM
This chapter assumes you have a working Jest setup from the earlier chapters. It also assumes you can create a component with createElement and attach it to document.body. You should know how a Lightning web component template renders for:each and conditional blocks. The goal is to find the elements a component rendered and check what they contain.
Why `element.querySelector` finds nothing
Lightning web components render their template inside a shadow root. This is a separate DOM tree attached to the host element. The host element is what createElement returns. Code inside the component reaches this tree with this.template.querySelector. A test reaches it with element.shadowRoot.querySelector.
Calling element.querySelector('.count') searches the host's light DOM. That tree holds only the children the test appended to the host itself, such as slotted content. It never contains template elements, so the call returns null.
The component under test
The examples use an itemList component. It shows a heading and a list of items. It shows an empty-state message and disables a refresh button when the list has no items.
force-app/main/default/lwc/itemList/itemList.html:
<template>
<h2 class="heading" data-id="heading">{heading}</h2>
<ul>
<template for:each={items} for:item="item">
<li key={item.id} class="item" data-id={item.id}>{item.label}</li>
</template>
</ul>
<p lwc:if={isEmpty} class="empty">No items to show</p>
<button class="refresh" disabled={isEmpty}>Refresh</button>
</template>force-app/main/default/lwc/itemList/itemList.js:
import { LightningElement, api } from 'lwc';
export default class ItemList extends LightningElement {
@api heading = 'Items';
@api items = [];
get isEmpty() {
return !this.items || this.items.length === 0;
}
}The class names and data-id attributes in the template give the test stable anchors to query by.
Rendering happens when you attach the element
The component renders when you call document.body.appendChild(element). This first render is synchronous. You can query right after appendChild with no await. Waiting is only needed after a later change. A later chapter covers that.
Set public properties before you attach the element. The first render then already reflects them.
import { createElement } from 'lwc';
import ItemList from 'c/itemList';
function createItemList(props = {}) {
const element = createElement('c-item-list', { is: ItemList });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-item-list rendering', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the heading', () => {
const element = createItemList({ heading: 'Fruit' });
const heading = element.shadowRoot.querySelector('.heading');
expect(heading.textContent).toBe('Fruit');
});
});A small factory such as createItemList keeps each test short. It also keeps the order of steps consistent: create, set properties, attach.
Choosing and using selectors
querySelector returns the first match or null. querySelectorAll returns a NodeList, which is a static list of every match. Both accept any CSS selector. Pick the selector that survives template changes.
| Selector | Example | Use it when | Risk |
|---|---|---|---|
| Class | `.heading` | The class marks a role in the component | Breaks if a stylist renames the class |
| Attribute | `[data-id="heading"]` | You want a hook that exists only for tests and tooling | Needs a template change |
| Tag name | `lightning-button` | You look for a child component or base component | Matches several if there are many |
| Structure | `ul > li:nth-child(2)` | Rarely | Breaks when markup is reorganized |
Prefer a class that describes the element's role, or a data-id attribute. Avoid selectors that mirror the nesting of the markup.
Assert on text, attributes, and state
After you hold a reference to an element, use its normal DOM properties.
it('renders one row per item with the right text and ids', () => {
const element = createItemList({
heading: 'Fruit',
items: [
{ id: 'a1', label: 'Apple' },
{ id: 'b2', label: 'Banana' }
]
});
const rows = element.shadowRoot.querySelectorAll('.item');
expect(rows).toHaveLength(2);
const labels = Array.from(rows).map((row) => row.textContent);
expect(labels).toEqual(['Apple', 'Banana']);
expect(rows[0].getAttribute('data-id')).toBe('a1');
expect(rows[1].dataset.id).toBe('b2');
});Some points about this test:
toHaveLengthworks on aNodeListbecause it has alengthproperty. It does not have array methods such asmap, so convert it withArray.fromfirst.textContentreturns the element's text exactly as rendered, with no escaping. If your template puts text on separate lines, the result can include extra whitespace. Call.trim()or usetoContainwhen you cannot control that.getAttribute('data-id')anddataset.idread the same attribute.toEqualcompares arrays by value.toBecompares by identity, which fails for two arrays with the same contents.
Other useful reads:
element.classList.contains('active')checks a CSS class.input.valuereads the current value of a form control.button.disabledis a boolean property.
Assert that something is not there
Conditional blocks such as lwc:if leave nothing in the DOM when the condition is false. The query returns null. Assert on that explicitly.
it('shows the empty state only when there are no items', () => {
const empty = createItemList({ items: [] });
expect(empty.shadowRoot.querySelector('.empty')).not.toBeNull();
expect(empty.shadowRoot.querySelector('.empty').textContent).toBe(
'No items to show'
);
expect(empty.shadowRoot.querySelector('.refresh').disabled).toBe(true);
const filled = createItemList({ items: [{ id: 'a1', label: 'Apple' }] });
const filledRoot = filled.shadowRoot;
expect(filledRoot.querySelector('.empty')).toBeNull();
expect(filledRoot.querySelector('.refresh').disabled).toBe(false);
});This test creates two elements without cleaning up between them. afterEach removes both once the test ends. Because both elements live in the same document, always query through the specific element's shadowRoot, never through document. A query on document cannot see inside any shadow root.
Common errors
- Querying before the element is attached. Until
appendChildruns, the shadow root is empty. Every query returnsnull. - Using
document.querySelector. It does not look inside shadow roots, so it cannot find template elements. - Using
element.querySelector. It searches the light DOM only. Useelement.shadowRoot.querySelector. - Calling array methods on a
NodeList. Wrap it withArray.from(...)or use afor...ofloop. - Asserting with
toBeon objects or arrays. UsetoEqualfor value comparison. - Asserting right after a change. If a property change or click happens after the first render, the DOM updates in a microtask. Wait for it before you assert, as the next chapter shows.
Exercises
Exercise
A test calls element.querySelector('.heading') on the host element of c-item-list and gets null, although the template contains <h2 class="heading">. What is wrong and how do you fix it?
Show answer
The query runs against the host's light DOM, but the h2 lives in the component's shadow root. Use element.shadowRoot.querySelector('.heading') instead.
Exercise
Write assertions that check c-item-list renders exactly three li rows when given three items, and that the second row's text is "Banana". Assume element is already created and attached, and the items are Apple, Banana and Cherry.
Show answer
const rows = element.shadowRoot.querySelectorAll('.item'); expect(rows).toHaveLength(3); expect(rows[1].textContent).toBe('Banana');
Exercise
Why does expect(element.shadowRoot.querySelectorAll('.item').map((r) => r.textContent)) throw, and what is the fix?
Show answer
querySelectorAll returns a NodeList, which has no map method. Convert it first with Array.from(element.shadowRoot.querySelectorAll('.item')).map((r) => r.textContent).