Sub topic 12
Work with base components and child components
This chapter covers how Jest treats the components your component renders inside its template. These are Lightning base components such as lightning-button, and your own child components such as c-contact-card. It assumes you can already create a component with createElement, query its shadow root, and wait for re-rendering. It also assumes you have a working sfdx-lwc-jest setup.
What happens to base components in Jest
Base components such as lightning-input and lightning-button are not implemented in your project. The sfdx-lwc-jest package ships replacements for them, called stubs. A stub is a small component with the same public properties and events as the real one, but with very little markup. The stubs let a template that uses lightning-* tags compile and render without an org.
Two consequences follow:
- Your component's own markup is real. The
lightning-buttonelement is created, and its public properties are set from your template. - The internals of the base component are not real. You cannot rely on the shadow DOM that the real component would render, such as the native
<button>insidelightning-button.
So test the contract between your component and the base component. That contract is the properties you pass in and the events you receive. Do not test how the base component draws itself.
A component to test
The examples use a small form component. It renders a lightning-input, a lightning-button, and a child component, c-contact-card.
<template>
<lightning-input
label="Name"
value={name}
onchange={handleChange}
></lightning-input>
<lightning-button
label="Save"
variant="brand"
disabled={isEmpty}
onclick={handleSave}
></lightning-button>
<c-contact-card contact-name={name}></c-contact-card>
</template>import { LightningElement } from 'lwc';
export default class ContactForm extends LightningElement {
name = '';
get isEmpty() {
return this.name.trim() === '';
}
handleChange(event) {
this.name = event.target.value;
}
handleSave() {
this.dispatchEvent(
new CustomEvent('save', { detail: { name: this.name } })
);
}
}The child component only needs a public property:
import { LightningElement, api } from 'lwc';
export default class ContactCard extends LightningElement {
@api contactName;
}<template>
<p class="card-name">{contactName}</p>
</template>Query base components by tag name
Query a base component from the parent's shadow root with its tag name. Because the stub is a real element with the real public API, you can read the properties your template set.
import { createElement } from 'lwc';
import ContactForm from 'c/contactForm';
describe('c-contact-form', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('passes the label and variant to the base components', () => {
const element = createElement('c-contact-form', { is: ContactForm });
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.label).toBe('Save');
expect(button.variant).toBe('brand');
});
});Reading input.label checks the property on the stub. It does not check the HTML attribute. Properties are what the parent actually passes, so they are the right thing to assert.
Simulate events from base components
Your handlers listen to events that base components fire. In a test, no user types into the stub, so you dispatch the event yourself. The change event from lightning-input carries the new value in event.target.value. Set the value on the stub first, then dispatch a change event on it.
it('enables the save button after the user types a name', async () => {
const element = createElement('c-contact-form', { is: ContactForm });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
const button = element.shadowRoot.querySelector('lightning-button');
expect(button.disabled).toBe(true);
input.value = 'Ada Lovelace';
input.dispatchEvent(new CustomEvent('change'));
await Promise.resolve();
expect(button.disabled).toBe(false);
});The await Promise.resolve() matters. The handler changes name, which marks the component for re-rendering. The disabled property on the button updates only after that render.
If the handler reads event.detail instead of event.target, pass the data in the event:
input.dispatchEvent(
new CustomEvent('change', { detail: { value: 'Ada Lovelace' } })
);Match the shape the real base component sends. Check the component's documentation in the Component Library when you are unsure.
Click a base component
For a lightning-button, click() on the stub element triggers your onclick handler. This works the same as clicking a native element.
it('fires save with the current name', async () => {
const element = createElement('c-contact-form', { is: ContactForm });
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('save', handler);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Ada Lovelace';
input.dispatchEvent(new CustomEvent('change'));
await Promise.resolve();
element.shadowRoot.querySelector('lightning-button').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.name).toBe('Ada Lovelace');
});Child components you wrote
A child component such as c-contact-card is rendered as real code. It runs its own constructor, its own template, and its own lifecycle hooks. Jest does not replace it with a stub unless you ask for that.
The parent's shadow root contains the child element. The child's own markup lives in the child's shadow root, which is a separate tree. A query on the parent cannot reach into it.
it('passes the name to the child component', async () => {
const element = createElement('c-contact-form', { is: ContactForm });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Ada Lovelace';
input.dispatchEvent(new CustomEvent('change'));
await Promise.resolve();
const card = element.shadowRoot.querySelector('c-contact-card');
expect(card.contactName).toBe('Ada Lovelace');
const cardText = card.shadowRoot.querySelector('.card-name');
expect(cardText.textContent).toBe('Ada Lovelace');
});Here the test asserts at two levels. The first assertion checks the contract: the parent passed contactName. The second checks the child's rendered output through card.shadowRoot. The second assertion works in this test because the child re-renders in the same microtask flush as the parent. If a child render depends on its own asynchronous work, add another wait.
The table shows where each query must start.
| You want to find | Query from |
|---|---|
| An element in the parent's template, including child component tags | `element.shadowRoot` |
| An element inside a child component's template | `child.shadowRoot` |
| Content passed into a slot | The parent that wrote the slotted markup |
Decide how much of the child to run
Running the real child keeps the test honest, but it also makes the parent's test depend on the child's behavior. A bug in c-contact-card can then fail the parent's tests. Use this guide:
- Test the parent against the child's public API (properties, methods, events). This is usually enough.
- Test the child's rendering in the child's own test file.
- Assert on
child.shadowRootonly when the parent's job includes affecting what the child shows, as in the example above.
When a child is expensive, for example because it calls Apex or a wire adapter, mock that dependency in the parent's test as covered in the earlier Apex and wire chapters. You can also replace the child entirely with a stub by creating a file under a jest-mocks folder and mapping it in jest.config.js with moduleNameMapper. Do this only when the child is hard to run, because every stub is a place where the test and the real component can drift apart.
Test events from child components
A child often dispatches a custom event that the parent handles. You can trigger the handler by dispatching the event from the child element.
it('handles a select event from the child', async () => {
const element = createElement('c-contact-form', { is: ContactForm });
document.body.appendChild(element);
const card = element.shadowRoot.querySelector('c-contact-card');
card.dispatchEvent(new CustomEvent('select', { detail: { id: '001' } }));
await Promise.resolve();
// assert on the effect of the parent's onselect handler here
});Dispatching the event yourself tests the parent's handler in isolation. Clicking inside the child tests the child and the parent together. Choose the first when you want the test to fail only for parent bugs.
Common errors
querySelectorreturnsnullfor a child's inner element. You queried the parent's shadow root. Querychild.shadowRootinstead.- A base component property is
undefined. The stub does not declare that property. Check that the property exists in the base component's documentation, and that thesfdx-lwc-jestversion is current. - An assertion on a base component's inner markup fails. The stub does not render the real internals. Assert on properties and events.
- A value is stale after a simulated event. Add
await Promise.resolve()after dispatching the event. - A handler receives
undefinedforevent.target.value. You dispatchedchangewithout settingvalueon the stub first.
Exercise
In a test for the parent, element.shadowRoot.querySelector('.card-name') returns null, although c-contact-card renders a paragraph with that class. Why, and how do you fix the query?
Show answer
The paragraph is in the child's shadow root, which is separate from the parent's. First get the child with element.shadowRoot.querySelector('c-contact-card'), then query card.shadowRoot.querySelector('.card-name').
Exercise
Your component handles onchange on a lightning-input by reading event.target.value. Write the two lines of test code that simulate a user typing "Grace" into the input, assuming input is the queried element.
Show answer
input.value = 'Grace'; followed by input.dispatchEvent(new CustomEvent('change'));. The value is set on the stub first because the handler reads it from event.target. Add await Promise.resolve(); before asserting on any re-rendered output.