Article 1 min read Free

Testing with Jest

Unit-test components with Jest and sfdx-lwc-jest: rendering, user interaction, events, and mocking Apex and wire.

Advertise with us 728 × 90

Testing with Jest

Lightning Web Components are tested with Jest, the popular JavaScript testing framework, via the @salesforce/sfdx-lwc-jest wrapper that knows how to render LWC. Unit tests run locally in Node — fast, no org required — and verify that a component renders correctly, reacts to input, dispatches the right events, and handles data and errors. Good Jest coverage catches regressions long before they reach an org.

Tests live in a __tests__ folder inside the component and follow a consistent rhythm: create the element, append it to the document to render it, then query its shadow DOM and assert. Because rendering is asynchronous, you await a microtask (commonly return Promise.resolve()) before checking the DOM.

import { createElement } from 'lwc';
import CartSummary from 'c/cartSummary';

describe('c-cart-summary', () => {
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('renders the total from its items', () => {
        const element = createElement('c-cart-summary', { is: CartSummary });
        document.body.appendChild(element);

        return Promise.resolve().then(() => {
            const total = element.shadowRoot.querySelector('p.total');
            expect(total.textContent).toBe('Total: 80');
        });
    });

    it('fires a select event when a tile is clicked', () => {
        const element = createElement('c-cart-summary', { is: CartSummary });
        const handler = jest.fn();
        element.addEventListener('select', handler);
        document.body.appendChild(element);

        return Promise.resolve().then(() => {
            element.shadowRoot.querySelector('button').click();
            expect(handler).toHaveBeenCalled();
        });
    });
});

The pattern is consistent: createElement builds the component, appendChild renders it, and shadowRoot.querySelector reaches into its DOM. You simulate interaction by calling click() or dispatching events, and assert with Jest matchers. To test events, attach a jest.fn() listener and assert it was called with the expected detail. Always clean up in afterEach so tests don't leak DOM between cases.

Two things make LWC tests robust. First, mock Apex by pointing Jest at a mock module for @salesforce/apex/... imports so tests don't need a server. Second, emit wire data using the wire adapters' test utilities (the emit method on a test adapter) to feed both success and error data into @wire properties, letting you assert how the component renders each branch. Test the states users actually hit — loading, data, empty, and error. With components tested, the final step is getting them into an org, which we cover next.

Enjoying this free lesson?

Namaste Salesforce is open and free. A star or a small sponsorship keeps it going.

Swarnil Singhai

Written by

Swarnil Singhai

Building Namaste Salesforce

Discussion