JEST Testing for lightning-tile LWC Actions

In this post, we will perform actions on lightning-tile component to cover on JEST testing.

Sample lightning-tile component:

lightning-tile-jest-class

Select Options in lightning tile Jest test

exTilejest.html

<template>
    <lightning-card title="A tile component for JEST Test class" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <p>Action Selected {tileAction}</p>
            <div class="slds-p-around_medium">
                <lightning-tile label="Marc Benioff" type="media" actions={myActions} onactiontriggered={handleAction}>
                    <lightning-icon slot="media" icon-name="standard:groups"></lightning-icon>
                    <p class="slds-truncate">Salesforce</p>
                </lightning-tile>
            </div>
        </div>
    </lightning-card>
</template>
exTilejest.js
import { LightningElement, track } from 'lwc';

export default class ExTilejest extends LightningElement {
    @track tileAction;
    @track myActions = [
        {label: 'Edit', value: 'edit', iconName: 'utility:edit'},
        {label: 'Delete', value: 'delete', iconName: 'utility:delete'}
    ];

    handleAction(event) {
        // Get the value of the selected action
        this.tileAction = event.detail.action.value;
    }
}
exTilejest.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="exTilejest">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>
exTilejest.test.js
import { createElement } from 'lwc';
import exTilejest from 'c/exTilejest';

describe('c-ex-tilejest', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('Clicking on Edit option', () => {
        // Create element
        const element = createElement('c-ex-tilejest', {
            is: exTilejest
        });
        document.body.appendChild(element);

        // get lightning-tile
        let btnElement = element.shadowRoot.querySelector('lightning-tile'); 
        btnElement.dispatchEvent(new CustomEvent('performAction', { detail: { action: { value: 'edit' } } } )); 
        
        return Promise.resolve()
        .then(() => {
            // Verify displayed greeting
            const div = element.shadowRoot.querySelector('p');
            expect(div.textContent).toBe('Action Selected:edit');
        }); 
    });
});

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation