JEST Setup For Salesforce

Prerequisites:
1 . Salesforce CLI, Visual Studio Code, Salesforce Extentions for Visual Studio Code, Node.js, npm installed and updated.
2. To confirm Node.js and npm is installed, In Visual Studio Code terminal, enter the following command respectively :
node --version
npm --version
3. Confirm the CLI is properly installed and on the latest version by running the following command:
sfdx update
4. If this commands fails then please run below:
npm update --global sfdx-cli
Setup :
1 . Run the following command in the top-level directory of your Salesforce DX project
sfdx force:lightning:lwc:test:setup
2 . If there is no package.xml at the root folder level, then an error will occur and below command needs to be executed first, followed by command mentioned in step 1:
npm init
3 . 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. and execute the command again
sfdx force:lightning:lwc:test:setup
4 . Execute below command to do a dry run to check if tests can be run:
node node_modules/@salesforce/sfdx-lwc-jest/bin/sfdx-lwc-jest
5 . If you encounter error – Invalid sourceApiVersion found in sfdx-project.json then update the sourceApiVersion in sfdx-project.json to the expected value.
6 . If you click on the beaker icon from the left hand navigation, LWC TESTS section will appear and can be used to run tests :
npm run test:unit
8 . At the time of installation if any dependency errpr occurs, Run below commands one by one in the top-level directory of your Salesforce DX project :
npm install --legacy-peer-deps
nmp install @salesforce/sfdx-lwc-jest --legacy-peer-deps
Article Information