Testing LWC with Jest
OVERVIEW
Jest tests are written, saved, and run differently than Jasmine or Mocha tests used for the Lightning Testing Service (LTS). Jest tests are local and run independently of Salesforce. Here are some best practices for Developers.
WHAT IS JEST TESTING FOR LIGHTNING WEB COMPONENTS?
Jest is a JavaScript testing framework. It helps in creating, structuring, and running tests for LWC. You can use Jest to write unit tests for Lightning Web Components. Jest also collects code coverage information and supports mocking, which helps isolate tests from complex dependencies.
SETTING UP THE JEST TEST FRAMEWORK
Node.js is JavaScript that runs on the Chrome browser engine. Npm is a package manager used for distributing reusable code modules.
- Install Node.js and npm: Download from Node.js (the long-term support version).
- Install the sfdx-lwc-jest Node module.
In the VS Code terminal, run the following command in the top-level directory of your Salesforce DX Project:
sfdx force:lightning:lwc:test:setup
Tests are written in local JavaScript files. Commit them to version control with the Lightning Web Component. Jest tests are local, saved, and run independently of Salesforce.
Salesforce CLI COMMAND
Use this command to create a test directory and a boilerplate test file:
sfdx force:lightning:lwc:test:create
Component Folder Structure
A folder named __tests__ is created at the top level of the component’s bundle directory: force-app/main/default/lwc/<Lightning Web Component Name>/__tests__/
All tests are saved in this folder.
TEST FILE NAMING CONVENTIONS
Jest runs JavaScript files in the __tests__ directory. Test files should end with .test.js.
EXAMPLE COMPONENT FILES
JEST TESTS FOR LIGHTNING WEB COMPONENTS
helloWorldJestTest.test.js
UNDERSTANDING THE JEST TEST FRAMEWORK
All tests should follow this structure:
- Imports: Import the createElement method to create the component under test.
- Describe() block: Defines the test suite.
- Cleanup: The afterEach() method resets the DOM after each test. This ensures one test’s output doesn’t affect another.
- it() block: Describes a single test.
- Asserts: Use assertions to check expected outcomes.
Conclusion
Jest offers a powerful and efficient framework for testing Lightning Web Components. By enabling developers to write unit tests locally, Jest enhances the reliability and maintainability of LWC applications. Understanding the setup process, folder structure, and test conventions is essential for effective testing. With Jest, developers can ensure their components function correctly and meet quality standards, ultimately leading to better performance and user experience in Salesforce applications.

