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
-
Create
Package.json
using the following commandnpm int -y
The Above command will generate the
package.json
file in the project with default values. -
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 foldernode_modules
get's generated after running the above command as shown below.
-
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
How to run test cases
- To run the test Once run the following command
npm run test:unit
- To keeps running the test cases run the following command which always keep an eye on the changes
npm run test:unit:watch
- To run the test cases in the debug mode run the following command
npm run test:unit:debug
- To get the coverage of your test case run the following command
npm run test:unit:coverage