Sub topic 1
Setting up Jest for LWC
Prerequisites
Assume you know LWC templates, @wire, Apex imports, JavaScript promises, and basic Jest terms such as describe, it, and expect.
Jest setup and the component under test
Jest is a JavaScript test runner. For Lightning Web Components, sfdx-lwc-jest supplies the browser-like environment and Salesforce module stubs.
A test creates the component with createElement, attaches it to document.body, and removes it after each test. The cleanup prevents one test's DOM from affecting another.
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 is option connects the custom element name to the component class. The component is not rendered until it is attached to the DOM.
Why data sources need mocks
A Jest test normally runs without a Salesforce org. It cannot make real Lightning Data Service requests or call Apex. A mock is a controlled replacement for that external data source.
Mocking lets a test choose the input and cover success, empty, and error paths. It also makes tests fast and repeatable.
Waiting for rendering
LWC updates the DOM asynchronously. A wire result or event handler may schedule work for a later promise turn. Wait before querying the DOM:
await flushPromises();Without this wait, an assertion can run before the template reflects the new data.
How `@wire` delivers data
The @wire decorator connects a property or function to a wire adapter. The adapter supplies a value containing either data or an error. In Jest, a test wire adapter lets the test call emit(data) or error() instead of contacting Salesforce.
Exercise
Why must a test attach an LWC to document.body before asserting its rendered output?
Show answer
Attaching it connects the component to the DOM, allowing its template and lifecycle behavior to run.