Run Jest Tests for Lightning Web Components

Run your unit tests frequently or continuously during component development.

Run Tests from VS Code 

If you install Salesforce Extensions for Visual Studio Code, you can run tests, debug them, and watch Jest files from within VS Code. For more information, see Salesforce Extensions for Visual Studio Code.

Run Tests on the Command Line 

To run all tests for your project, use the Salesforce CLI command sf force lightning lwc test run from the root folder of your project. Otherwise, run the command that you added to the scripts block of your project’s package.json file when installing Jest and dependencies .

1npm run test:unit

Run Tests Continuously During Development 

To run all tests for a single component every time you save changes, go to the component directory and run the sfdx-lwc-jest command with the --watch parameter. Use the entry that you added to the scripts block of your project’s package.json file when installing Jest and dependencies.

1npm run test:unit:watch

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

Run Jests Tests in 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.

  • VS Code Salesforce Extension Pack
  • Chrome Developer Tools
  • VS Code debugger advanced configuration

The VS 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.

Advanced Jest Configurations 

sfdx-lwc-jest is configured to run Jest tests without any additional changes. However, if you’re an advanced Jest user, check out some of Jest’s other configuration options. See github.com/salesforce/sfdx-lwc-jest#overriding-jest-config.

If your Jest tests are executing slowly and they have dependencies from different folders, provide mappings to speed up the resolution. See the moduleNameMapper in the lwc-recipes repo.

Important

See Also