JEST Setup

Prerequisite for Jest in LWC

To setup Jest in your LWC project. You should have the nodejs and npm installed in your machine.

The official Node.js website has installation instructions for Node.js:

https://nodejs.org

The Node.js installer includes the NPM package manager

How to check node and npm is installed.

node -v or node --version
npm -v or npm --version

Jest Setup

  1. Create Package.json using the following command

    npm int -y

    The Above command will generate the package.json file in the project with default values.

  2. Install sfdx-lwc-jest node module

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

    The Above command will install the salesforce/sfdx-lwc-jest package that is helpful to run the jest test cases. You can see a new folder node_modules get's generated after running the above command as shown below.

fig: node_modules with sfdx-lwc-jest package
fig: node_modules with sfdx-lwc-jest package

  1. Run Your Jest Test Cases using the following command

    node ./node_modules/@salesforce/sfdx-lwc-jest/bin/sfdx-lwc-jest

If you don't have any test cases in the project it will return 0 test found.

Automate Jest Scripts

If you see how complicated to run the test cases as shown above in step 3. Let's make our life easier by adding automated scripts.

Add the following scripts to your package.json

"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"

Your package.json will look like something as shown below

package.json look
package.json look

How to run test cases

  1. To run the test Once run the following command
npm run test:unit
  1. To keeps running the test cases run the following command which always keep an eye on the changes
npm run test:unit:watch
  1. To run the test cases in the debug mode run the following command
npm run test:unit:debug
  1. To get the coverage of your test case run the following command
npm run test:unit:coverage
Site developed by Nikhil Karkra © 2024 | Icons made by Freepik