Testing Lightning Web Components

By in
667
Testing Lightning Web Components

Today, we are going to review how to test Lightning Web Components (LWCs) with jest tests.

First, create local JavaScript files for your component tests. Together with the component itself, commit them to version control. Salesforce does not save Jest tests.

Compared to Jasmine or Mocha tests created for the Lightning Testing Service, Jest tests are authored, saved, and executed differently. Salesforce is not involved in the saving or running of Jest tests; they are solely run locally.

The Salesforce CLI command sfdx is available.

Lightning Web Components LWC Jest Testing
Image Source: Salesforce

 

Force:lightning:lwc:test:create

to build a boilerplate test file and a test directory for it. The myButton Lightning web component may be tested by creating a test directory and file with the following command.

 

sfdx force:lightning:lwc:test:create -f

force-app/main/default/lwc/myButton/myButton.js

 

Component Folder Organization

After using the create command in the Salesforce CLI, your component’s bundle directory, such as force-app/main/default/lwc/myButton/ tests__, will have a subdirectory named __tests__ at its top level. Create the folder yourself if not. The __tests__ folder should contain all of the component’s tests. By submitting the __tests__ folder to version control, tests can be shared with other team members or systems.

 

Update .forceignore

Add this glob pattern to the.forceignore file for each of your projects to make sure the __tests__ folder and its contents are never saved to Salesforce. This task is completed for you using the Salesforce CLI command sfdx force:lightning:lwc:test:setup.

**/__tests__/**

The __tests__ folder and its contents are ignored by Salesforce DX commands that push, pull, or transform code and metadata thanks to this design.

 

Testing File Naming Protocols

__tests__ directory JavaScript files are executed by Jest. We advise that tests finish in.test.js, but test files must have names that end in.js. You can either have many files to group related tests or a single file with all of your component tests. Subfolders can contain test files.

 

Conclusion

In this way, we learned an overview of testing LWCs with jest tests.

 

To learn more about Lightning Web Components, check out some of my related blogs below!

 

Additional Resources

Cover Photo by . . on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *