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:
The Node.js installer includes the NPM package manager
node -v or node --version npm -v or npm --version
Package.json using the following command
npm 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 folder
node_modules get's generated after running the above command as shown below.
Run Your Jest Test Cases using the following command
If you don't have any test cases in the project it will return 0 test found.
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"
package.json will look like something as shown below
npm run test:unit
npm run test:unit:watch
npm run test:unit:debug
npm run test:unit:coverage