Sub topic 2
Creating a component under test
This chapter assumes you know basic Lightning Web Components (templates, decorators, lifecycle hooks), basic Jest (describe, it, expect, jest.fn), and promises with async/await. It also assumes sfdx-lwc-jest is already installed in your project. Here you build the test skeleton that every later chapter reuses.
Why a component needs to be created by hand
In the browser, the Lightning runtime creates your component for you. In Jest there is no runtime, so your test must do that work. The lwc module exports createElement, which builds a custom element from a component class. You then attach the element to document.body, which runs the same lifecycle that a real page runs: the constructor, then connectedCallback, then the first render.
A component that is created but never attached does not connect. Wires are not provisioned and the template is not rendered. Attaching it is part of the test setup, not an optional step.
The steps
- Import
createElementfromlwc. - Import the component class by its namespace and name, such as
c/contactList. - Call
createElementwith a tag name and theisoption. - Set any public properties (
@api) on the element. - Append the element to
document.body. - Wait for pending promises, then assert on
element.shadowRoot.
The tag name is a label for the test. It is conventionally c- plus the kebab-case component name.
A working skeleton
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('renders the component', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(element.shadowRoot).not.toBeNull();
});
});Read it in three parts.
- Creation.
createElement('c-contact-list', { is: ContactList })returns a real DOM element. Nothing has rendered yet. - Attachment.
document.body.appendChild(element)triggersconnectedCallbackand the first render pass. - Waiting. LWC renders asynchronously, so
flushPromisesreturns a promise that resolves after the current queue of pending promises has run. It usessetTimeoutwith a delay of 0, which runs after all queued microtasks. The next chapter covers this in detail.
Setting public properties
Public properties are set on the element before you attach it. This matches how a parent template passes values at creation time.
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);Setting a property before attachment means the first render and any wire that depends on it already see the value. Setting it after attachment also works, but it triggers a second render, so you must wait again before asserting.
Querying the rendered output
LWC components use synthetic shadow DOM in Jest, and the root is available as element.shadowRoot. Use it for all queries:
const items = element.shadowRoot.querySelectorAll('li');
const error = element.shadowRoot.querySelector('.error');Do not use document.querySelector to find elements inside the component. It does not see into the shadow tree. Elements rendered by child components, such as lightning-input, are also stubs. You can query for them and set their properties, but their internal markup is not available.
Cleaning up after each test
The afterEach block removes every child of document.body. Without it, elements from earlier tests stay connected and keep reacting to emitted wire data. That causes confusing cross-test failures. jest.clearAllMocks() resets call history on mocks so that toHaveBeenCalledWith checks only see the current test. Later chapters return to this under test isolation.
Exercise
In what order should a test create the element, set an @api property, and attach it to the DOM, and why?
Show answer
Create it with createElement, set the @api property, then call document.body.appendChild. Setting the property first means the first render and any wire that depends on it already see the value. Attaching triggers connectedCallback and rendering, so the test should then wait (for example with flushPromises) before asserting on element.shadowRoot.
Exercise
Why does the skeleton remove all children of document.body in afterEach?
Show answer
Elements from earlier tests would stay connected and could still react to emitted data or errors. Removing them gives each test a clean DOM and prevents failures that depend on test order.