Jest 101 for LWC- Part 2 : Writing the jest test.

Palash Dubey
Cloudwerx
Published in
4 min readFeb 6, 2022

A quick guide to get started with Jest and snippets to help you to get started !

Check out Part 1 : Setup & Terminologies in case you haven't for the setup process and terminologies !
In this blog we will jump into the actual code.

Some abbreviations used in the blog -
JT : jest test
cmp : component

Creating element :

We would need to import the lwc into JT first. To do so, we import the ‘createElement’ and the component as well, in the following example, the name of the cmp is ‘assetsListView’ :

// import the createElement and the js class, this will be needed  // for all the jest cases
import { createElement } from 'lwc';
import assetsListView from 'c/assetsListView';

Adding the body :

(1) We create the cmp and now we add it in dom .(Refer #1 in snippet below).We use ‘createElement’ to create the lwc cmp.

(2) Now we add the cmp to the html document using appendChild. (Refer #2 in snippet below)

test('First test to show list view', () => {

//#1
const element = createElement(‘c-icassets-list-view’,{
is:icassetsListView
});
// #2 : Now we need to append it to body.
document.body.appendChild(element);

As soon as we append the child this will also start the lifecycle of cmps. So for instance, your connectedCallback method would be called as well.

For our example, this would be our HTML file :

And JS file would be :

Now we write the before each inside ‘describe’ block as follows :

Now we write a test class to check the ‘titleName’

Checking the tile name which we set via ‘@api’

In the above snippet, we also use ‘jest.clearAllMocks’ to clear the mock.calls, mock.instances and mock.results properties of all mocks. (More details : here)

Child cmp:

To check if a child cmp is being rendered or not, we can directly query the child cmp by the tag name.

In case you need to verify, if the child cmp in which we have a “assetName” property decorated with “@api”. (Refer the AssetsList.html above)
Now we need to check if it has the correct data, you can first fetch the child cmp and then directly get ‘assetName’ property :

const childCmpElement = element.shadowRoot.querySelectorAll(‘c-assets-residential-property-list’);
expect(childCmpElement.assetName).toBe('Monkey D.Luffy');

Setting API value:

Now, in case you want to set some values for the variables with ‘@api’ property, we add it via the element variable. For exmaple :

test(‘Test case for single picklist rendering’, () => {
const element = createElement(‘c-test-cmp’,{
is:testCmp
});
//Pass data to element
element.label = "test123"
..
..

Here label is decorated with ‘@api’ in the testCmp.js

Checking event/lifecycle hook completion:

Suppose in a scenario we want to check if the connectedCallback is completed or a event is completed and only after that we want to check if the HTML is rendered properly, then we can use

return Promise.resolve().then(() => {    //Fetch the cmp here and then write the assert. For example :     const getSpanTag = element.shadowRoot.querySelector(‘section.slds-is-open’);
console.log(‘getSpanTag — ‘,getSpanTag); // This will be null
expect(getSpanTag).toBe(null);
})

The whole test case would look something like this :

For Loop example :

In case you need to check the iteration,

Now we simple get the component with the style “nameBold” using ‘querySelectorAll’ and check its length.

const nameDivs= element.shadowRoot.querySelectorAll('div.nameBold');
expect(nameDivs.length).toBe(3);
//Suppose you have 3 records to iterate.

In case you need to verify if the data you supplied via the jest and the data which are rendering are correct, you can store the result in a array and cross-check the rendered values with the values set in ‘assetList’ variable.
For more details you can check Nikhil’s video here : click.

Setting data for jest:

Now in case you are calling apex method/wire method and need to return some values to the js code, we need to store that result in JSON format , in a data folder.
For better visibility create a ‘data’ folder in “__tests__” and then create folder specific to which decorator you want to load the data.
For example :

Creating data for jest.

In case of Apex, create a folder named apex, inside it create a folder with the class name. Inside this folder create the json and, name them as per method and their usage. (Refer the image above.)
Now, we need to import these JSONs in our JT file. So we will import them using :

const PICKLIST_CONFIGURATIONS = require('./data/api/picklistFieldData.json')
//This is the path to JSON.

As you can see we give the path to the file, which in our case is in “data” folder➡“api” folder. The path needs to be surrounded by single quotes.

Now to use in test case you can directly write as :

test('Test to check the value of titleName api value', () => {
//Fetch the ul tag which has the class list-view-accordion
const element = document.querySelector('c-assets-list-view');
const getTitleName = element.shadowRoot.querySelector('span.slds-accordion__summary- content');
element.configurations= PICKLIST_CONFIGURATIONS; expect(getTitleName.innerHTML).toBe('default title name');
});

Now with the basics ready, you can dive into more examples on the lwc-recipes github repo : click here. Here you will find LWC as well the jest test for various examples which you might need in your project.

Happy coding !

--

--

Palash Dubey
Cloudwerx

Certified Salesforce Tech lead with 7+ years of experience. Exceptionally good at problem solving, finding practical solutions & implementing them.