Andy Tran

Start LWC Testing using Jest

by | 24 Jul, 2022 | Salesforce | 2 comments

Start LWC Testing using Jest

The development of Apps in Salesforce has changed a lot if we look back to 2014. Salesforce and its developer community has seen the migration from developing traditional Visual Force pages to modern Single-Page Applications framework like Aura (Lightning Components) and now accommodating the newest technologies with the help of Lightning Web Components (LWC) for building enterprise-scale applications natively for modern JavaScript browsers.

What is LWC & Why it’s important to test them?

Unlike AURA, LWC uses modern ES6 or later standards to develop modern web apps, this makes LWC fast, lightweight, and better at security with improved API support for third-party APIs. It also automatically provides polyfill for older browsers that do not support all underlying web standards like shadow DOM, web components, etc.

“All code is guilty until proven innocent”

Testing is very important when it comes to the LWC. LWC components contain many different files including – HTML, JS Controllers, CSS, and Configurations. To have a production-ready code – it is a good practice to test components in isolation to verify API methods and events, user interactions like clicks, DOM outputs, and event fires.

Tools for testing LWC Components

The main advantage of LWC is that it has built-in Test-Driven Development (TDD), which makes tests easy to understand. Below are some widely used tools in Salesforce to test LWC

    • Jest
    • Jasmine
    • Mocha
    • QUnit

Why Jest?

Jest is a testing framework of JavaScript mainly designed to ensure the JavaScript codebase preciseness and accuracy for unit testing. Jest works with almost all JavaScript frameworks and libraries. It is simple to use and can be easily extended to include various integration tests. Jest provides rich features for writing JS tests that are independent of any platform and can be executed locally.

    • Fast and Safe
    • Excellent Code Coverage
    • Easy Mocking
    • Great Exceptions
    • Great Community Support
    • Well Documented

Pre-requisite for Jest in LWC

  1. Download Visual Studio Code (or any other compatible IDE)
  2. Install node.js (with npm)
  3. Verify node and npm are installed
    1. node –v or node –version
    2. npm –v or npm –version

Jest Setup

  1. Create json file in Salesforce DX Project by running the command as “npm init -y” from the terminal of the Visual Studio Code
  2. Install sfdx-lwc-jest node package and its dependencies.
    NOTE: sfdx-lwc-jest works only in Salesforce DX projects.

    1. npm install
    2. npm install @salesforce/sfdx-lwc-jest –save-dev
  3. By default, an SFDX project will include below mentioned script entries in the “scripts” block of json file. If the project’s file doesn’t include them and adds them manually.

SFDX project

JEST basics

Let’s take a look at some basics of writing tests with Jest.

Describe Blocks

If we want to group all the tests for a specific class describe block can be used. We can further nest new describe blocks in an existing describe block. Describe block defines a test suite.Describe Blocks

“It” or “Test” Blocks

We use the test keyword to start a new test case definition. It keyword is an alias for the test keyword. It blocks describe a single testIT Blocks

OR"Test" Blocks

beforeEach and afterEach

If we have some statements that need to be executed for each test case. For that, we can use the beforeEach and afterEach functions to avoid code duplication. Both functions allow us to execute logic before or after each test.beforeEach and afterEach

beforeAll and afterAll

In some cases, you only need to do the setup once, at the beginning of a file. This can be especially used when the setup is asynchronous, so you can’t do it inline. Jest provides beforeAll and afterAll functions to handle this situation.beforeAll and afterAll

Matchers

A matcher is used for creating assertions in combination with the expected keyword. We want to compare the output of our test with a value we expect the function to return.

Matchers
The complete list of matchers can be found here: https://jestjs.io/docs/using-matchers

Create a LWC component:

Before testing LWC, let’s create a basic LWC component first.

  • Create a component called welcomeMessage
  • Create a folder __tests__ under welcomeMessage component
  • Add __tests__ folder in your .forceignore file so that it’s not deployed to org
  • Add the following code to: html file

Create a component called welcomeMessage

Create a Jest Test File:

Create a file with your component name – WelcomeMessage.test.js

Create a Jest Test File

Writing our First test for the component (WelcomeMessage.test.js)Writing our First test for the component (WelcomeMessage.test.js)

Code Clarification for – welcomeMessage.test.js file

  • We are importing the createElement method from the lwc that will help us to create a new element
  • Also importing our WELCOMEMESSAGE component from the Project Path – c/WelcomeMessage
  • We have created the describe block for organizing test cases in logical groups. Let’s give the scenario name to test as – WelcomeMessage Component Test and within this block, we are writing our test cases
  • afterEach() method resets the DOM at the end of the test.
  • In the – it block, we need to create an instance of the original LWC to test by “createElement()”
  • After that, we need to add the component instance into the DOM by appendChild
  • Now, we need to get elements from the DOM using querySelector() Finally, we need to put the expect statement which is an assertion of the success condition. where the value of div.textContent will match the string in toBe() method.

Run your test case

You can run your test case using the following commandRun your test case

Output

After running the test cases you will see the following output indicating our tests have been passed with assertions.Output

Summary

Testing LWC components in Salesforce is still an unexplored horizon. Testing modern apps with lightweight LWC components for modern browsers requires thorough testing. Jest can help us with this – provided our tests are well written and cover all the spices of feature validations.

Also Read: LWC : Share Data Between Parent and Child Components

Thank you for checking out our blog! If you’re seeking top-notch Salesforce-related services for your company, look no further. Erudite Works is a leading Salesforce consulting services provider, offering expert strategies, implementation, and customization of Salesforce CRM to enhance your business’s automation and reporting needs. Our certified team ensures the development of a seamless CRM solution and delivers exceptional consulting services. Contact Us to learn more about how we can optimize your business processes.

Share this article...

2 Comments

  1. Jyothi

    Thank you for sharing this useful information. Keep up the good work!

    Reply
  2. Mark Green

    Why we should choose Jest over Mocha? Can you please ellaborate. Thankyou in advance

    Reply

Submit a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.