Jest Tests for Lightning Web Components

Join us to learn about how to write Jest for Lightning web components(LWC) testing. Jest tests are written, saved, and run differently than Jasmine or Mocha tests written for the Lightning Testing Service (LTS). Jest tests are local only, and are saved and run independently of Salesforce. Let see how to Test Lightning Web Components using Jest Test Framework.

What is Jest Testing for Lightning Web Components?

JEST is a Javascript testing framework for writing Javascript tests. This framework helps in creating, structuring & running of LWC Jest tests. Use Jest to write unit tests for Lightning Web Components.

Jest framework can collect the code coverage information and also supports mocking that helps to isolate tests from complex dependencies.

Set up Jest Test Framework

Node.js is a Javascript built on Chrome browser Javascript engine. Npm is a package manager utilized for distribution of reusable code modules.

Install Node.js together with npm (Installation of Node.js will automatically install npm) https://nodejs.org/en/download/ (long-term support version)

Install sfdx-lwc–jest Node module

In the VS Code terminal, execute the following command in the top-level directory of Salesforce DX Project.

sfdx force:lightning:lwc:test:setup

For more in detail steps, use this trailhead link – https://trailhead.salesforce.com/content/learn/modules/test-lightning-web-components/set-up-jest-testing-framework

Component tests are written in local JavaScript files. Commit them to version control along with the Lightning Web component. Jest tests are local only, saved and run independently of Salesforce.

Salesforce CLI Command – 

sfdxforce:lightning:lwc:test:create [To create a test directory and a boilerplate test file]

Component Folder Structure

A Folder name __tests__ is created at the top level of the component’s bundle directory (force-app/main/default/lwc/<Lightning Web Component Name>/__tests__.). All the tests are saved in the __tests__ folder.

Test File Naming Conventions

Jest framework runs the Javascript files in the __tests__ directory. Test files should end with .test.js.

helloWorldJestTest.html

<template>
    <lightning-card title="Hello World" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <p>Hi, {message}</p>
            <lightning-input label="Name" value={greeting} onchange={handleChange}></lightning-input>
        </div>
    </lightning-card>
</template>

helloWorldJestTest.js

import { LightningElement } from 'lwc';

export default class HelloWorldJestTest extends LightningElement {
   message = 'JEST Test!';
  
  handleChange(event) {
    this.message = event.target.value;
  }
}

helloWorldJestTest.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
  <apiVersion>55.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>
JEST Tests for Lightning Web Components

helloWorldJestTest.test.js

import { createElement } from 'lwc';
import HelloWorldJestTest from 'c/helloWorldJestTest';

describe('c-hello-world-jest-test', () => {
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('To Display message', () => {
        const element = createElement('c-hello-world-jest-test', {
            is: HelloWorldJestTest
        });

        document.body.appendChild(element);

        const div = element.shadowRoot.querySelector('div');
        expect(div.textContent).toBe('Hi, JEST Test!');
    });
});

Understand Jest Test Framework

All the tests should have the structure mentioned below:

Imports:

This method is available only for tests. The test imports the createElement method. Code must import the component to test later to create the component under test.

Describe() block:

It defines the test suite. 

Cleanup:

The afterEach() Jest method resets the DOM at the end of the test. Every test has a single instance of DOM and changes aren’t reset b/w tests. As a best practice it’s important to clean up b/w tests so that one tests output doesn’t affect another test.

it() block:

A single it() block is used to describe a single test.

Asserts:

The expected statement is an assertion of the success condition. Get the elements from the DOM using querySelector() method.

Summary

I hope this post helped you to understand the Jest Test Framework and write Jest Tests for Lightning Web Components. If you are new to LWC checkout our FREE Lightning Web components training.

Ravi Teja
Ravi Teja

Salesforce Consultant at Global Consulting Firm
12x Salesforce Certified Application Architect

Articles: 9

Leave a Reply

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