Jest For Testing Lightning Web Components

Lightning Web Components (LWC) serves as a framework to create swift, reusable, and effective web components tailored for Salesforce. Among its standout features, LWC boasts the capability to seamlessly conduct component testing with Jest, a widely used JavaScript testing framework. This blog post delves into the significance of Jest testing for LWC, the steps to install Jest within your LWC project, and provides illustrative code samples.

Numerous reasons underscore the importance of writing Jest tests for your LWC components:

  1. Maintaining Code Quality: Developing tests for your components enables the early detection of bugs and problems during the development phase, leading to potential time and resource savings. This practice ensures that your code performs as intended and that any alterations made do not disrupt existing functionalities.

2. Streamlines Refactoring: A robust test suite instills confidence when modifying your code, such as refactoring, by mitigating concerns about introducing new bugs.

3. Encourages Sound Development Practices: Test writing prompts a more modular perspective on code, fostering better design and increasing code reusability.

4. Aids Continuous Integration/Continuous Deployment: Implementing tests simplifies automating the deployment process by integrating them into the CI/CD pipeline, ensuring code functionality before production deployment.

5. Simplified Debugging: A well-defined set of tests streamlines issue pinpointing within the code, expediting the resolution process.

Conduct Jest tests for the following purposes:

  • Assessing a component independently
  • Evaluating a component’s public API (including @api properties, methods, and events)
  • Validating fundamental user interactions (such as clicks)
  • Confirming the DOM output of a component
  • Verifying the expected firing of events

In summary, leveraging Jest to test your LWC components offers numerous advantages, significantly enhancing code quality, maintainability, and reliability.

Setup or Installing

Add <em><strong>sfdx-lwc-jest</strong></em> and its dependencies to every Salesforce DX project. Note that sfdx-lwc-jest operates exclusively within Salesforce DX projects.

Requirements or Preconditions

Prior to installing <em><strong>sfdx-lwc-jest</strong></em>, ensure Node.js and npm are installed.

  • This page displays two Node.js releases. We advise opting for the “LTS” (Long-Term Support) version over the “Current” version.
  • Upon installing Node.js, npm is automatically installed. However, you might need to update npm separately. Refer to the npm website for guidance on updating.
Utilize the Salesforce CLI to install Jest and its dependencies into your project.

The easiest method to install Jest and its dependencies is by executing the Salesforce CLI command: sfdx force:lightning:lwc:test:setup. Run this command from the main directory of each Salesforce DX project. It generates essential configuration files and handles the installation of the sfdx-lwc-jest package.

Manually set up Jest and its dependencies.


If you’re in an environment where the Salesforce CLI isn’t available, you can manually configure your test dependencies.

To install sfdx-lwc-jest and its dependencies, execute these commands once from the primary directory of each Salesforce DX project:

npm install npm install @salesforce/sfdx-lwc-jest --save-dev

By default, an SFDX project includes script entries within its package.json file. If your project’s file lacks them, ensure to add these entries.

{
  ...
  "scripts": {
    ...
    "test": "npm run test:unit",
    "test:unit": "sfdx-lwc-jest",
    "test:unit:watch": "sfdx-lwc-jest --watch",
    "test:unit:debug": "sfdx-lwc-jest --debug",
    "test:unit:coverage": "sfdx-lwc-jest --coverage",
    ...
  },
  ...
}

Below is a basic Lightning Web Component (LWC) named “c-hello-world” that showcases the message “Hello, World!”:

<template>
    <p>Hello, World!</p>
</template>

And here’s a Jest test designed for this component:

import { createElement } from 'lwc';
import HelloWorld from 'c/helloWorld';

describe('c-hello-world', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('displays the correct message', () => {
        // Create element
        const element = createElement('c-hello-world', {
            is: HelloWorld
        });
        document.body.appendChild(element);

        // Get message from component
        const message = element.shadowRoot.querySelector('p');
        expect(message.textContent).toBe('Hello, World!');
    });
});

To execute the test, utilize the Salesforce CLI by running the following command:

Execute the command: npm run test:unit

Continuously execute all tests for a specific component whenever changes are saved by navigating to the component directory and initiating the sfdx-lwc-jest command with the “–watch” parameter. Employ the entry you previously added to the scripts block within your project’s package.json file when Jest and its dependencies were installed.

Execute the command: npm run test:unit:watch

Jest actively monitors all component files for changes and executes pertinent tests each time it identifies an alteration.

In summary, incorporating Jest for testing your Lightning Web Components (LWC) stands as a crucial measure to guarantee code quality, sustainability, and reliability. By detecting bugs early, facilitating refactoring, fostering robust development practices, and streamlining deployment automation, testing becomes an integral part of the development cycle. The installation of Jest is simple, requiring minimal configuration, allowing you to promptly initiate test writing for your components. Additionally, it serves as an efficient debugging tool. Following the steps outlined in this blog post, you can seamlessly set up Jest in your LWC project and commence crafting tests for your components. With a comprehensive suite of tests, you can confidently ensure your code functions as expected and modifications won’t disrupt existing functionalities.

Thank you for exploring this blog post on testing Lightning Web Components with Jest. We trust that the shared insights were beneficial and informative. For further updates on similar topics, consider subscribing to our blog. Subscribers receive notifications regarding new posts and updates, ensuring access to the latest information and trends in LWC development. To subscribe, enter your email address in the subscription box on our website, becoming part of our mailing list. We eagerly anticipate your subscription, continuing to deliver valuable content for your developmental journey.