Test LWC with Jest

Jest is a powerful JavaScript testing framework for the client-side project. It’s supported in any React Application, Node, Babel, TypeScript as well as Salesforce Lightning Web Component.Jest uses jsdom to provide an environment like a browser’s Document Object Model(DOM).

Jest can be used for

  • Test a component in isolation
  • Test a component’s public API (@api properties and methods, events)
  • Test basic user interaction (clicks)
  • Verify the DOM output of a component
  • Verify that events fire when expected

In this session, we will see how to test a simple Lightning Web Component using Jest framework.

To test Lightning Web Component, need to install sfdx-lwc-jest and its dependencies into Salesforce DX Project. jsdom is downloaded during the installation of lwc-jest.

First, we need to set up the environment to work with Jest in Salesforce DX project.

  • Install Node.js from this link:  https://nodejs.org/en/, if you have not installed in your computer yet. Set the Environment Path to access npm from any drive location.
  • Generally, Salesforce DX Project doesn’t have a package.json file. Run the following command as “npm init” from the terminal of the Visual Studio Code and it will create a package.json file in the project directory. After “npm init” execution, system will ask you the project information, for now you can keep it as blank. You just need to enter until package.json file has been created.
  • To install lwc-jest and its dependencies, please run the following commands one by one:
npm install
npm install @salesforce/sfdx-lwc-jest --save-dev

It will take some time to complete the downloading of sfdx-lwc-jest and its dependencies in your SFDX project library.

  • Need to update the <scripts> block of the package.json file by adding the following codes.
"test:unit": "lwc-jest",
"test:unit:watch": "lwc-jest --watch",
"test:unit:debug": "lwc-jest --debug",
"test:unit:coverage": "lwc-jest --coverage"

N.B.- Please check the latest release on sfdx-lwc-jest, may be you need to update “lwc-jest” to “sfdx-lwc-jest” for “test:unit” snippet if the upper code snippets will not work.

  • Create a folder named “__tests__” in the specific Lightning Web Component folder in the SFDX project.
  • Update the .forceignore file to ensure that the files of the “__tests__” folder should not be deployed during deployment of the lightning web component into the Salesforce Org. Please update the “.forceignore” file  according to the following line:

           **/__tests__/**

Setup is done. Awesome!! You have done a great job. Take rest..we will move to the next section how to run Jest to test Lightning Web Component.

Naming Convention of Test File: LightningWebComponentName.test.js

Now, we will create the test file into the “__tests__” folder.

Let’s say following is the Lightning Web Component named “welcomeWindow”

welcomeWindow.html

<template>
    <lightning-card title="Welcome My Friends">
        <div class="messageClass">    
            <lightning-layout><!--if horizontal-align="space", all layout items will be in center-->
                    <lightning-layout-item flexibility="auto" padding="around-small"> 
                        <div class="contentClass">                   
                            Welcome to LWC Training Class
                        </div>
                    </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>     
</template>

After that, we will create a welcomeWindow.test.js file into the “__tests__” folder. Now we will write the code into this file like:

welcomeWindow.test.js

import { createElement } from 'lwc';
import WELCOMEWINDOW from 'c/welcomeWindow';

describe('c-welcome-window', () => {
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('displays greeting', () => {
        // Create element
        const element = createElement('c-welcome-window', {
            is: WELCOMEWINDOW
        });
        document.body.appendChild(element);
        // Verify displayed welcome message
        const div = element.shadowRoot.querySelector('div');
        expect(div.textContent).toBe('Welcome to LWC Training Class');
    });
});

Clarification of the welcomeWindow.test.js file

  • Imports standard methods: First, we need to import the standard “createElement” method and import the Lightning Web Component to test. Here, we will test “welcomeWindow” Lightning Web Component.
  • Describe() block: Next, we will focus on the describe block. This block is nothing but a test suite. A single describe block can be used to test more business cases. afterReach() method resets the DOM at the end of the test.
  • it block: We can say it block as test block. A single it block describes a single test.
  • Component Creation: In the it block, we need to create an instance of the original LWC to test by “createElement()” method.
  • Adding the Component into DOM: After that, we need to add the component instance into the DOM by appendChild method.
  • Asserts: Now, we need to elements from the DOM using querySelector() method. Finally, we need to put the expect statement which is an assertion of the success condition. Here, we have written just like:

expect(div.textContent).toBe(‘Welcome to LWC Training Class’); //where the value of div.textContent will match the                     string in toBe() method.

Jest supports lots of matchers like toBe and toMatchObject. Please check all the methods from this link:
https://jestjs.io/docs/en/expect

How to run the test?

Now, we need to run the following code in the terminal of VS Code to test our lightning component.

npm run test:unit

When this command will be executed, it will run the respective code snippet “lwc-jest” mentioned in the script block of the package.json file.

So, after running this command, we will get the following output in the terminal of our VS Code.

 

 

 

 

 

 

 

if we will update the welcomeWindow.test.js file with line no. 19 as

expect(div.textContent).toBe('Welcome to Lightning Web Component Training Class');

and run the unit test again, we will see the error message as mentioned in the following image


 

 

 

 

 

 

 

 

 

 

 

Thank you!! So, we have explored how to test a simple Lightning Web Component(LWC) with Jest library. In the next session, we will see how to test LWC with the different type of decorators.

16,329 total views, 6 views today

Rating: 5.0/5. From 3 votes.
Please wait...
This entry was posted in Lightning Components, Lightning Web Component. Bookmark the permalink.

Leave a Reply