Sub topic 12
Work with base components and child components
This chapter assumes you can already render a component with createElement, query its shadow root, and wait one microtask for re-rendering. It also assumes you know how @api properties and custom events connect a parent to its children.
What Jest renders for each kind of child
Most components contain other components. Jest treats the two kinds differently.
- Base components such as
lightning-inputandlightning-buttoncome from thelightningnamespace. Thesfdx-lwc-jestpackage replaces each one with a stub. A stub declares the public properties and events of the real component, but it has no behavior, validation, or styling. - Your own child components such as
c-status-badgeare the real code. Jest imports and renders them inside the parent's test.
Because stubs do no real work, you test the contract: which properties the parent sets and which events it handles. How the base component draws itself is not your concern.
A parent with both kinds of child
The parent uses two base components and one custom child. File: force-app/main/default/lwc/nameEntry/nameEntry.html.
<template>
<lightning-input label="Name" value={name} onchange={handleChange}></lightning-input>
<lightning-button label="Save" variant="brand" onclick={handleSave}></lightning-button>
<c-status-badge text={status}></c-status-badge>
</template>File: nameEntry.js.
import { LightningElement } from 'lwc';
export default class NameEntry extends LightningElement {
name = '';
status = 'Idle';
handleChange(event) {
this.name = event.detail.value;
}
handleSave() {
this.status = this.name ? 'Saved' : 'Name required';
}
}The child, in statusBadge, takes one public property. File: statusBadge.html.
<template>
<span class="badge">{text}</span>
</template>File: statusBadge.js.
import { LightningElement, api } from 'lwc';
export default class StatusBadge extends LightningElement {
@api text;
}Test the contract with each child
Query children from the parent's shadow root, using the tag name. Read the properties the parent set. To simulate user input, dispatch the event the real component would fire.
import { createElement } from 'lwc';
import NameEntry from 'c/nameEntry';
describe('c-name-entry', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('passes static attributes to base components', () => {
const element = createElement('c-name-entry', { is: NameEntry });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
const button = element.shadowRoot.querySelector('lightning-button');
expect(input.label).toBe('Name');
expect(button.variant).toBe('brand');
});
it('shows "Saved" in the child after a name is entered', async () => {
const element = createElement('c-name-entry', { is: NameEntry });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.dispatchEvent(new CustomEvent('change', { detail: { value: 'Ada' } }));
element.shadowRoot.querySelector('lightning-button').click();
await Promise.resolve();
const badge = element.shadowRoot.querySelector('c-status-badge');
expect(badge.text).toBe('Saved');
});
it('shows "Name required" when saving an empty name', async () => {
const element = createElement('c-name-entry', { is: NameEntry });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await Promise.resolve();
const badge = element.shadowRoot.querySelector('c-status-badge');
expect(badge.text).toBe('Name required');
});
});The test never types into a real input. It dispatches a change event with the same detail shape the real lightning-input produces, and the parent's handler runs as it would in an org.
Common errors
querySelectorreturnsnull. You querieddocumentorelementinstead ofelement.shadowRoot. Child elements live inside the parent's shadow root.- A property reads
undefinedon a stub. The stub does not declare that property. Check the stub's source innode_modules/@salesforce/sfdx-lwc-jest/src/lightning-stubs. - Stale values after an event. You asserted before the
await. Re-rendering is asynchronous, so wait one microtask first. - A custom child makes the test fail. The real child code runs, so its errors surface in the parent's test. Fix the child, or test the parent with a simpler child.
Exercise
In a parent test you need to check that lightning-button received label="Save", and that the parent reacts when the user types in a lightning-input. Which element do you query from, and how do you simulate the typing?
Show answer
Query from element.shadowRoot, for example element.shadowRoot.querySelector('lightning-button').label. The base component is a stub, so no real typing happens. Dispatch the event the real component fires, for example input.dispatchEvent(new CustomEvent('change', { detail: { value: 'Ada' } })), then await Promise.resolve() before asserting on any re-rendered output.