Sub topic 4
Render a component with createElement
This chapter assumes you have a working Jest setup from sfdx-lwc-jest and know the basic describe, it, and expect structure. It also assumes you know LWC fundamentals: templates, @api properties, and lifecycle hooks. Here you will learn how a test creates a component, attaches it to a document, and reads back what it rendered.
Why tests need createElement
In a Salesforce org, the platform creates your component for you. A parent template includes <c-counter>, or an app page places it. In a Jest test there is no parent and no page, so the test has to do that work.
LWC provides one function for this: createElement, exported from the lwc module. It builds an instance of your component class and returns it as a standard DOM element. From that point you can treat the result like any other HTML element. You set properties, add event listeners, append it to the document, and query it.
import { createElement } from 'lwc';
import Counter from 'c/counter';
const element = createElement('c-counter', { is: Counter });The c/counter import path works because sfdx-lwc-jest maps the c namespace to the component folders in your project. The imported Counter is the component's class, not an instance.
The createElement signature
createElement takes two arguments.
| Argument | Meaning |
|---|---|
| Tag name | The name of the custom element to create, such as `'c-counter'`. It must be a valid custom element name in kebab case, with a namespace prefix and a hyphen. |
| Options object | An object with an `is` key. Its value is the component constructor you imported. |
The tag name is only a label for the element you get back. It does not have to match the folder name, but matching it (c-counter for the counter folder) keeps failures easy to read. Browser DOM output and error messages show this tag name.
The call returns an HTMLElement. Nothing has rendered yet at this point. The component exists, but it is not connected to a document.
Component lifecycle in a test
The lifecycle of the element follows the DOM. The component's constructor runs during createElement. The connectedCallback runs when you append the element to the document. The first render happens right after that. The disconnectedCallback runs when you remove the element.
This order has a practical consequence. If you want a component to see a value in its first render, set the public property before you append the element. If you set it after appending, the component renders once with the old value and then re-renders, and your assertions must wait for that re-render. The next chapters cover waiting. For now, prefer setting properties first.
Attach the element to the document
An element that is not connected does not render, and its connectedCallback does not run. The standard approach is to append it to document.body:
document.body.appendChild(element);Jest runs your tests in a simulated browser environment (jsdom), so document and document.body exist without a real browser.
Here is a complete test that creates the counter component, sets a property, attaches it, and checks the first render:
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter rendering', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders an initial count of 0', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
const countEl = element.shadowRoot.querySelector('.count');
expect(countEl.textContent).toBe('0');
});
it('uses the step property when it is set before attaching', () => {
const element = createElement('c-counter', { is: Counter });
element.step = 5;
document.body.appendChild(element);
expect(element.step).toBe(5);
});
});The first test needs no await. The first render happens synchronously when appendChild runs, so the DOM is ready on the next line. Waiting becomes necessary only after something changes following that first render.
Reach the rendered output through shadowRoot
The component's template renders inside its shadow root. From the test, you reach it through element.shadowRoot. Querying document or document.body directly will not find elements inside the component, because the shadow DOM hides them from outside queries.
const button = element.shadowRoot.querySelector('button');Two points are specific to LWC's test setup:
element.shadowRootis available in tests even though the component's own code does not expose it to outsiders in production. Thesfdx-lwc-jestsetup runs components with the synthetic shadow polyfill, and it opens the root so tests can inspect it.- Content that a parent passes into a
<slot>is not part of the child's shadow tree. It belongs to the light DOM of the host element. To find slotted content, query the element itself, such aselement.querySelector(...), notelement.shadowRoot.
The next chapter covers querying and assertions in more depth. The point here is that createElement gives you the host element, and shadowRoot is the door to what it rendered.
Setting properties and calling methods
Public properties marked @api are available on the element as ordinary properties. Public methods marked @api are available as ordinary methods.
const element = createElement('c-counter', { is: Counter });
element.step = 2; // @api property
document.body.appendChild(element);Only @api members are reachable. Private fields such as count in the counter are not exposed on the element, so element.count is undefined. This is by design. Test the visible behavior through the DOM and events, not through private state. Tests that read internal fields break whenever you refactor, even when behavior does not change.
Common errors
These problems appear often when you first use createElement:
- Forgetting to append the element.
element.shadowRoot.querySelector(...)returnsnull, because nothing rendered. The error then shows up on the next line asCannot read properties of null. Check thatappendChildran before the query. - Passing the wrong value to
is.{ is: Counter }needs the default export of the component module. If you import with curly braces or from the wrong path,createElementthrows an error about an invalid constructor. - Using a tag name without a hyphen. A name such as
'counter'is not a valid custom element name. Use'c-counter'. - Querying
documentinstead ofshadowRoot.document.querySelector('.count')returnsnullfor content inside a component. Query throughelement.shadowRoot. - Reusing one element across tests. State from one test leaks into the next. Create a fresh element in each
itblock. The cleanup chapter explains how to remove old elements.
A helper for repeated setup
When many tests build the same component, a small helper reduces repetition. Keep it plain so each test still shows what it sets up.
import { createElement } from 'lwc';
import Counter from 'c/counter';
function createCounter(props = {}) {
const element = createElement('c-counter', { is: Counter });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-counter with a helper', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders with default properties', () => {
const element = createCounter();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
it('accepts a step before the first render', () => {
const element = createCounter({ step: 3 });
expect(element.step).toBe(3);
});
});Object.assign sets each property before appendChild runs, so the first render already has the values. The helper returns the element so tests can still add listeners and query it.
Edge cases
- Setting an
@apiproperty after attaching. This works, but it triggers a re-render. Assertions that read the DOM must wait for it. - Appending to an element other than
document.body. You can append to any element that is itself in the document. The component connects once its ancestors are connected. - Creating without attaching. This is useful for checking that a constructor does not throw, or for setting properties in bulk. It is not enough for anything that depends on rendering.
- Reading a public getter and setter. An
@apigetter and setter pair behaves like a normal property on the element. The setter runs when you assign the value, even before attaching.
Exercise
A test creates a component, appends it to document.body, and then runs element.step = 4 before reading the DOM. Why can the DOM show the old value, and how could you change the test so the first render already uses 4?
Show answer
The component renders when it is appended, using the properties it has at that moment. Setting step afterwards triggers a re-render that has not happened yet when the next line reads the DOM. Set element.step = 4 before calling document.body.appendChild(element), so the first render already uses the new value. If the property must change after attaching, wait for the re-render before asserting.
Exercise
A test calls document.querySelector('.count') and gets null, although the component clearly renders an element with class count. Name two possible causes.
Show answer
Either the element was never appended to the document, so nothing rendered, or the query was made on document instead of element.shadowRoot. The shadow DOM hides the component's internal elements from queries on document. Append the element first, then query through element.shadowRoot.querySelector('.count').