Sub topic 2
Creating a Component Under Test
This chapter covers how a Jest test builds a Lightning Web Component, puts it on the page, and removes it again. Every later chapter relies on this skeleton, so it is worth getting right before any mocking starts.
Prerequisites
This chapter assumes you know:
- Basic Lightning Web Components: templates, decorators (
@api,@wire), and lifecycle hooks such asconnectedCallback. - Basic Jest:
describe,it,expect, andjest.fn. - JavaScript promises and
async/await.
You also need a Jest setup that uses @salesforce/sfdx-lwc-jest, which the previous chapter covered. Your test files live in a __tests__ folder next to the component's JavaScript file.
What "component under test" means
In production, the Lightning runtime creates your component. It reads the markup of a parent component or a Lightning page, makes an instance, and inserts it into the page.
In Jest there is no parent and no page. Your test has to play that role. The component you are testing is called the component under test. To create it, you:
- Import the component class.
- Build an element from it with
createElement. - Set any public properties.
- Append the element to
document.body. - Inspect what it rendered.
Jest runs in a simulated browser called jsdom, so document and document.body exist. They are not a real browser, but they are close enough for LWC rendering.
Creating the element
createElement is exported by the lwc module. It takes a tag name and an options object.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
const element = createElement('c-contact-list', { is: ContactList });Three details matter here.
- The tag name uses kebab case with the namespace prefix. The component folder
contactListin the default namespacecbecomesc-contact-list. The name you pass should match this convention, even though in a test it only labels the element. - The
isoption takes the component's constructor. You get it from the default export of the imported module. - Creating the element does not run
connectedCallbackand does not render. Nothing happens until the element is attached to the DOM.
The c/contactList import path works because sfdx-lwc-jest maps the c/ namespace to your force-app module folders. If you see "Cannot find module 'c/contactList'", the folder is not listed in sfdx-project.json, or the name is misspelled.
Attaching to the DOM
An element that is not in the document is inert. Appending it triggers the lifecycle.
document.body.appendChild(element);When you call appendChild, the engine runs the constructor, sets up @wire connections, runs connectedCallback, and renders the template. The initial render happens synchronously as part of this call for simple templates. Work that depends on promises, such as wire results or Apex responses, finishes later. That is the subject of the chapter on flushing promises. For now, keep in mind that anything asynchronous needs a wait before you assert on it.
Setting public properties
Public properties are the ones decorated with @api. Set them on the element before you append it, so the component sees them the first time it renders and in connectedCallback.
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);If you set the property after appending, the component rerenders. That is a valid thing to test, but it is a different scenario. A wire whose configuration depends on recordId will first run with undefined in that case.
Only @api properties are reachable from outside. Private fields, and properties without a decorator, are not on the element. Test through the public surface and the rendered output instead of reaching into the component's internals.
A first test
Here is the skeleton that the rest of the tutorial extends.
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();
});
});The pieces, in order:
flushPromisesreturns a promise that resolves on the next timer tick. By then, promise callbacks that were already queued have run. Awaiting it gives the component time to react to data.afterEachremoves everything fromdocument.bodyand clears mock call history. This keeps one test from affecting the next.- The test creates the element, attaches it, waits, and then makes an assertion.
The assertion here is deliberately weak. It only proves that the component was created and rendered a shadow root. A real test checks specific output, as the next section shows.
Reading the rendered output
LWC components use synthetic shadow DOM. The element's rendered content is available through element.shadowRoot, and you query it with the usual DOM methods.
const items = element.shadowRoot.querySelectorAll('li');
expect(items.length).toBe(2);
const heading = element.shadowRoot.querySelector('h2');
expect(heading.textContent).toBe('Contacts');Keep these rules in mind:
- Query from
element.shadowRoot, not fromdocument. Content inside a component is not visible todocument.querySelector. querySelectorreturnsnullwhen nothing matches. Calling.textContentonnullthrows aTypeError. When an element may be missing, assert that it exists first, or assert that it isnullfor the negative case.- Child components such as
lightning-inputare stubs in Jest. You can find them and read the properties your component set on them, but they do not render real Salesforce UI. Their inner markup is not available. - Prefer stable selectors, such as a class or
data-attribute that you add for testing, over selectors tied to layout likediv > div:nth-child(2).
The lifecycle at a glance
The diagram shows what happens during one test, and where your code runs.
Why cleanup matters
Each element you append stays in document.body until something removes it. Jest does reuse the same jsdom document across the tests in a file. Without cleanup, three problems appear:
- A later test can find an element left over from an earlier test and assert against the wrong one.
- Components that were never disconnected keep their wire connections, so they can receive data that a later test emits.
disconnectedCallbacknever runs, so any cleanup logic in your component is not exercised.
The afterEach loop in the skeleton fixes all three. Removing the element triggers disconnectedCallback and detaches the wires. Test isolation gets a full chapter later. For now, copy the pattern into every test file.
Creating a fresh element in each test
Create the element inside each it, not once at the top of the file. A shared element carries state from one test to the next, and it hides ordering bugs.
If many tests repeat the same three lines, wrap them in a small helper.
import { createElement } from 'lwc';
import RecordName from 'c/recordName';
function mountRecordName(props = {}) {
const element = createElement('c-record-name', { is: RecordName });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-record-name', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('accepts a record id', () => {
const element = mountRecordName({ recordId: '001000000000001AAA' });
expect(element.recordId).toBe('001000000000001AAA');
});
it('can be mounted without a record id', () => {
const element = mountRecordName();
expect(element.recordId).toBeUndefined();
});
});The helper creates a new element on each call, so tests stay independent. It sets properties before attaching, so the component sees them on first render.
Testing events and public methods
The element is also your way to interact with the component from outside.
- To call a public
@apimethod, call it on the element:element.refresh(). - To listen for an event the component dispatches, add a listener to the element before the action that triggers it.
const handler = jest.fn();
element.addEventListener('contactselect', handler);
element.shadowRoot.querySelector('li').click();
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail).toEqual({ id: '001' });Register the listener before you trigger the event. A listener added afterward misses it.
Common mistakes at this stage
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module 'c/contactList'` | Folder missing from `sfdx-project.json`, or a misspelled name | Check the package directories and the folder name |
| `element.shadowRoot` is `null` | Using a different mode, or the component is not created through `createElement` | Create it with `createElement` and read `shadowRoot` from that element |
| Nothing is rendered | The element was never appended to `document.body` | Call `appendChild` |
| `querySelector` returns `null` for a child element | The element is rendered conditionally, or data has not arrived yet | Wait with `flushPromises`, and check the `if:true` condition |
| Property is `undefined` in `connectedCallback` | Property was set after `appendChild` | Set it before appending |
| A test sees DOM from another test | No cleanup between tests | Add the `afterEach` cleanup |
Practice
Exercise
A test creates an element with createElement, sets element.recordId, and only then calls document.body.appendChild(element). Another test appends first and sets recordId afterward. How does the component's first render differ, and which version is safer for a component that wires on recordId?
Show answer
In the first test the component sees recordId during its constructor setup, wire connection, and connectedCallback, so the wire runs once with the real value. In the second test the component first renders with recordId undefined, then rerenders after the property is set, and the wire is reconfigured. Setting the property before appending is safer for the usual case. The second order is only right when you are deliberately testing how the component reacts to a later change.
Exercise
Why do tests query element.shadowRoot.querySelector instead of document.querySelector, and what happens if you call .textContent on the result of a selector that matched nothing?
Show answer
The component's markup lives inside its shadow root, so document.querySelector cannot see it. When a selector matches nothing, querySelector returns null, and reading .textContent on null throws a TypeError. Assert that the element exists first, or assert null when you expect it to be absent.
Exercise
Write the afterEach block that removes every element from document.body and clears mock call history. Name one problem it prevents.
Show answer
afterEach(() => { while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } jest.clearAllMocks(); }); It prevents a component from an earlier test staying connected, which could receive data emitted in a later test or be found by a later query.