Skip to main content

Set Up Jest Testing Framework

Learning Objectives

After completing this unit, you'll be able to:

  • Describe the Jest test framework.
  • Describe the role of Node.js and npm.
  • Install Node.js and npm.
  • Install the @salesforce/sfdx-lwc-jest JavaScript module in a Salesforce DX project.

Before You Begin

To complete this module, you need Salesforce CLI, Visual Studio Code, and Salesforce Extensions for Visual Studio Code installed and updated. To fulfill these prerequisites, we recommend that you complete the Quick Start: Salesforce DX, Quick Start: Visual Studio Code for Salesforce Development, and Quick Start: Lightning Web Components projects before you go on.

We're taking a test-driven development (TDD) approach, where we'll write the Jest test before we write the component that it tests. Because of this, each test will initially fail. Then we'll update the component to get the Jest test to pass.

Create a Salesforce DX Project

The first step before testing is to create a Salesforce DX project to store your Lightning web components and Jest tests.

  1. In Visual Studio Code, open the Command Palette by pressing Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS).
  2. Enter sfdx.
  3. Select SFDX: Create Project. If you don't see this option, complete the prerequisites from this module's first unit before you go on.
  4. Select Standard.
  5. Enter test-lwc as the project name.
  6. Press Enter.
  7. Select a folder to store the project.
  8. Click Create Project and wait for the new Visual Studio Code window to open.
  9. Click View, then choose Terminal. This opens a terminal window inside Visual Studio Code. The terminal defaults to the top-level directory of the project. You need the terminal later to run commands in the working directory of this project.

What Are Node.js and npm?

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine and npm is a package manager for distributing reusable code modules. In the universe of Node.js and npm, these reusable code modules are known as Node modules. In Salesforce terminology, a Node module—reusable code that can be easily distributed to multiple projects—is similar to unlocked packages.

Node.js and npm are popular tools in a modern JavaScript developer's toolbox. Learn more about modern JavaScript in the Learn to Work with JavaScript trail.

Install Node.js and npm

Jest is a Node module, so to use it you need to install Node and npm. Let's do that now.

  1. Install Node.js from https://nodejs.org/en/download/. We recommend using the LTS (long-term support) version.
  2. Confirm Node.js is installed. In the Visual Studio Code terminal we opened earlier, enter the following command.
    node --version
    You should see output like v16.13.0 or a later version.
  3. When you install Node.js, npm also installs automatically.
    In a terminal, enter the following command.
    npm --version
    You should see output like 8.1.0 or a later version. It's a good idea to keep npm updated.
    Note

    You may need to update npm, so visit the npmjs documentation for more details on upgrading npm for different operating systems.

What Is Jest?

Jest is a powerful tool with rich features for writing JavaScript tests. Jest can collect code coverage information and supports mocking to help isolate tests from complex dependencies. Jest tests don't run in a browser or connect to an org, so they run fast. Use Jest to write unit tests for all of your Lightning web components. To run Jest tests for Lightning web components, you need the @salesforce/sfdx-lwc-jest Node module in your Salesforce DX project.

Note

Jest tests work only with Lightning web components in Salesforce DX projects, they don't work with Aura components. For Aura components, see Testing Components with Lightning Testing Service.

Install sfdx-lwc-jest Node Module

The @salesforce/sfdx-lwc-jest Node module lets you write, run, and debug Jest tests for Lightning Web Components. The Salesforce CLI makes it easy to install Jest and its dependencies into the project.

  1. Confirm the CLI is properly installed and on the latest version by running the following command from the command line.
    sf update
    You should see output like cli: Updating CLI....
  2. In the Visual Studio Code terminal, run the following command in the top-level directory of your Salesforce DX project:
    sf force lightning lwc test setup
    This installs npm and @salesforce/sfdx-lwc-jest into the project. Results should look like this:
    Setup messages in terminal.
    Note

    If you receive an error “No matching version found for prettier-plugin-apex@^1.10.1”, update the package.json file devDependencies prettier-plugin-apex to ^1.10.0.
    package.json file with updated prettier-plugin-apx.

    You may notice the process finds some vulnerabilities. For our purposes that's fine. These are not the vulnerabilities you are looking for.

Note

For other ways to install the Jest Node module, Salesforce makes available the @salesforce/sfdx-lwc-jest Node module as a JavaScript package on npm at https://www.npmjs.com/package/@salesforce/sfdx-lwc-jest and as an open-source project on GitHub at https://github.com/salesforce/sfdx-lwc-jest.
Run these npm commands in the top-level directory of your Salesforce DX project:
npm install
Then:
npm install @salesforce/sfdx-lwc-jest --save-dev

Run Jest Tests

Excellent, you set up your Salesforce DX project to be able to run the Jest tests that you write later in this module. There are several ways to run the Jest tests now that everything is set up. You can call the script directly, use npm commands, or you can use clicks in Visual Studio Code. You can run one test or all tests in a file or project. You can even run tests automatically when the code the test covers is changed.

Let's take a look at the different ways you can run Jest tests.

The sfdx-lwc-jest Node Command

You can run the script directly from where it was installed in the project using the following Node command.

  1. In the Visual Studio Code terminal, in the top-level directory of the Salesforce DX project, enter the following command.
    node node_modules/@salesforce/sfdx-lwc-jest/bin/sfdx-lwc-jest
    There are no Jest tests yet so you should see output like No tests found, exiting with code 1.
    Note

    If you get an “Invalid sourceApiVersion” error it is due to an updated VS Code Extension with the latest Salesforce release.
    error Invalid sourceApiVersion found in sfdx-project.json. Expected 51.0, found 52.0

    1. In Visual Studio Code, in the top-level directory, open sfdx-project.json.
    2. Update the line of code with “sourceApiVersion” to the Expected version from the error message you received.
      "sourceApiVersion": "51.0"
    3. Save the file.

That's a great start, but let's look at how we can make it even better with automation.

Automate Test Scripts with Package.json and npm

A goal of having unit tests is to promote developers to write and run them as part of their development and continuous integration process so that bugs are identified and fixed sooner rather than later. Having to remember and type long commands like the one above over and over is counterproductive to your goal. Here's where automation comes in.

npm has some great out-of-the-box script automation flexibility. Running the install earlier added a series of options to the scripts property of the package.json file at the root of your project.

{
  "name": "test-lwc",
  ...  "scripts": {
    ...
    "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",
    ...
  },
  ...}

If you want to run all tests for your project, run this npm command from the base directory of your project.

npm run test:unit

If you want to run tests in a specific directory, using the command above in a specific directory will run only the tests in that directory. This allows you to isolate what you are testing.

Run Tests Continuously During Development

For this option, Node relies on Git to “watch” the code. To use this option, be sure to have Git initialized for your project. To run all tests for a single component every time you save changes, change directories to the component directory and run the npm command below that utilizes sfdx-lwc-jest with the --watch parameter. As mentioned above you could also run this from the base of the project and have all tests in the project run for every change.

npm run test:unit:watch

Jest now watches all component files for updates and runs all relevant tests every time it detects a change.

Run Tests in Jest Debug Mode

Running Jest tests in debug mode is useful if you want to step through your tests and app code to find out why your tests or code aren't behaving as expected. You can debug Jest tests using the following tools.

  • Visual Studio Code Salesforce Extension Pack
  • Chrome Developer Tools
  • Visual Studio Code debugger advanced configuration

The Visual Studio Code Salesforce Extension Pack provides the simplest and most straightforward option, while Chrome DevTools caters to seasoned web developers. Additionally, the advanced configuration for the VS Code debugger enables you to work with different debuggers and debugging scenarios. The advanced configuration offers the most flexible option for debugging your Jest tests.

For more information, see Debug Jest Tests for Lightning Web Components or for information about troubleshooting Jest issues, see Jest: Troubleshooting.

Run Tests and Display Code Coverage

To see the code coverage of the tests, use the --coverage option below.

npm run test:unit:coverage

Run Tests with Clicks in Visual Studio Code

The Salesforce Visual Studio Code extensions give a lot of control and visual feedback for running Jest tests. It gives you options to run single, multiple, or all tests. It also gives you the ability to use the --watch option on a file since Git is preinstalled in Visual Studio Code.

Click the test beaker icon Test beaker button icon. to open the Test sidebar. If you don't see the icon, then you may need to create a new SFDX project. In the Test sidebar there is an LWC Tests section that displays any Jest tests that are in the project. Here is what the test sidebar looks like with tests in your project.

LWC Tests in Test sidebar in the test-lwc project.

Click the play button Test play button icon. to run a test or multiple tests in a project. Hover your cursor over the directory or individual test to display the play button. When a test runs, the results display in the terminal. The results are also indicated by color in the sidebar. Green means passing. Blue indicates not run, orange shows a skipped test, and red indicates a failing test. Clicking the test in the sidebar opens the file and takes you right to that test.

Click the refresh icon Test refresh button icon. to clear the test results.

There are also direct controls in the test file view.

Test file view in Visual Studio Code.

Click the play button Test play button icon. in the main toolbar to run all the tests in the file. You can also click Run Test above each test in the file to run that specific test.

To run all the tests in the file every time you save changes, click the watch icon Test watch button icon. in the main toolbar. It's a great option to use when you are working on tests in the file.

Wow! That's a lot to take in.

Alright, let's write some tests.

Resources

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities