Data Binding and Events testing

In this blog you will learn the following topics

  1. How to create a test file
  2. How to run a test file
  3. How to test Data Binding
  4. How to test on change event
  5. How to use beforeEach block

Create a LWC component for testing

  • First create a component called myEventTesting
  • Add the following code to the myEventTesting.js, myEventTesting.html and myEventTesting.js-meta.xml files
myEventTesting.js
import { LightningElement, track } from 'lwc';

export default class MyEventTesting extends LightningElement {
    @track greeting = 'World';

    handleChange(event) {
        this.greeting = event.target.value;
    }
}
myEventTesting.html
<template>
    <lightning-card title="HelloBinding" icon-name="custom:custom14">
        <div class="slds-var-m-around_medium">
            <p>Hello, {greeting}!</p>
            <lightning-input label="Name" value={greeting} onchange={handleChange}></lightning-input>
        </div>
    </lightning-card>
</template>
myEventTesting.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="templateToggleDemo">
        <apiVersion>49.0</apiVersion>
        <isExposed>true</isExposed>
        <targets>
            <target>lightning__AppPage</target>
            <target>lightning__RecordPage</target>
            <target>lightning__HomePage</target>
          </targets>
</LightningComponentBundle>

The component we have created has a greeting property which is initialized with value World. In template we are binding greeting property to <p> tag. Also we have a lightning-input field which has a onchange event which call the handleChange handler. handleChange handler update the value of greeting property.

Create Your Jest Test File

  1. Add a __tests__ folder under your component
  2. Add __tests__ folder to .forceignore so that it’s not deployed to your org
  3. Create a file with your component name myEventTesting.test.js and give an extension .test.js as shown below.

fig: Component with test file package
fig: Component with test file package

Create Your test cases for the component

myEventTesting.test.js
import {createElement} from 'lwc'
import MyEventTesting from 'c/myEventTesting'

describe('c-my-event-testing suite', ()=>{
    beforeEach(()=>{
        const element = createElement('c-my-event-testing', {
            is: MyEventTesting
        })
        document.body.appendChild(element)
    })
    test('Test default greet value should be Hello, World!', ()=>{
        const element = document.querySelector('c-my-event-testing')
        const text = element.shadowRoot.querySelector('p')
        expect(text.textContent).toBe('Hello, World!')
    })
    test('Test default greet value should not be Hello, Nikhil!', () => {
        const element = document.querySelector('c-my-event-testing')
        const text = element.shadowRoot.querySelector('p')
        expect(text.textContent).not.toBe('Hello, Nikhil!')
    })

    test('test input change event value', ()=>{
        const element = document.querySelector('c-my-event-testing')
        const inputElement = element.shadowRoot.querySelector('lightning-input')
        inputElement.value='Salesforce'
        inputElement.dispatchEvent(new CustomEvent('change'))
        const text = element.shadowRoot.querySelector('p');
        return Promise.resolve().then(()=>{
            expect(text.textContent).toBe('Hello, Salesforce!')
        })
    })
})

In line 1. we are importing the createElement method from the lwc that will help us to create a new element

In line 2. We are importing our MyEventTesting from the path ie. c/myEventTesting

In line 4. We have created the describe block for organizing test cases in logical groups of tests. We have given the name c-my-event-testing suite name to the describe block and within this block, we are writing our test cases

In line 5-10 We have created the beforeEach block. This blocks Runs before each of the tests in this file runs. Within this block, we are creating the element using createElement method and loading the HTML of our myEventTesting component within the element that we are creating. Once element is ready, we are attaching the element to the JSDOM body tag.

In line 11. We have created test block in which we are going to test that our p tag has the has content Hello, World! or not

In line 16. We have created another test block in which we are going to test that our p tag text with another matcher

In line 22. We have created another test block in which we are going to test that our on change event is the value of p tag is updating or not.

In line 28. We are using the Promise.resolve() to make sure onChange event has updated the DOM because DOM updation is an asynchronous process.

Run Your test cases

You can run your test case using the following command

npm run test:unit -t myEventTesting // this command for running single file

npm run test:unit // this command for running all the test files

Output

After running the test cases you will see the following output

fig: test cases output
fig: test cases output

Site developed by Nikhil Karkra © 2024 | Icons made by Freepik