JEST Test class for LWC Toast Notifications

 In this post, we will see how to cover code for frequently used toast messages in lightning web components.

First, we will create a simple LWC component to show a toast message then will create a JEST test class for that.
lwc-jest-toast

LWC Toast Messages (platformShowToastEvent) JEST Test

exToastMessage.html
<template>
    <lightning-card title="JEST test for Toast Messages" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <lightning-button label="Show Toast" onclick={showNotification}></lightning-button>
        </div>
    </lightning-card>
</template>
exToastMessage.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ExToastMessage extends LightningElement {
    showNotification() {
        const evt = new ShowToastEvent({
            title: 'Success',
            message: 'Hello World',
            variant: 'success'
        });
        this.dispatchEvent(evt);
    }
}
exToastMessage.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="exToastMessage">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>
Now follow steps to create JEST test for Toast events:

Step:1
Here we are creating toast mock implementation for the project level. so it can be used in any component to test toast messages.
Create a folder structure like this: In force-app folder create folder test--> jest-mocks --> lightning --> platformShowToastEvent.js
toast-event-mock

platformShowToastEvent.js
/**
 * For the original lightning/platformShowToastEvent mock that comes by default with
 * @salesforce/sfdx-lwc-jest, see:
 * https://github.com/salesforce/sfdx-lwc-jest/blob/master/src/lightning-stubs/platformShowToastEvent/platformShowToastEvent.js
 */
export const ShowToastEventName = 'lightning__showtoast';
export class ShowToastEvent extends CustomEvent {
    constructor(toast) {
        super(ShowToastEventName, {
            composed: true,
            cancelable: true,
            bubbles: true,
            detail: toast
        });
    }
}
Step:2
Now create Jest.config.js config file if not created yet and add the above file location.Jest.config.js
jest-config-file
<pre><code class="language-js">const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
    ...jestConfig,
    moduleNameMapper: {
        '^lightning/platformShowToastEvent$':
            '<rootDir>/force-app/test/jest-mocks/lightning/platformShowToastEvent'
    }
};</code></pre>
Step:3
Setup is done. now write a jest test class for our component.
exNavigationMixinJest.test.js
import {createElement} from 'lwc';
import {ShowToastEventName} from 'lightning/platformShowToastEvent';
import ExToastMessage from 'c/exToastMessage';
describe('c-ex-toast-message', () =>{
    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('Test Toast message', () => {
        const TOAST_TITLE = 'Success';
        const TOAST_MESSAGE = 'Hello World';
        const TOAST_VARIANT = 'success';
        // Create initial element
        const element = createElement('c-ex-toast-message', {
            is: ExToastMessage
        });
        document.body.appendChild(element);
        // Mock handler for toast event
        const handler = jest.fn();
        // Add event listener to catch toast event
        element.addEventListener(ShowToastEventName, handler);
        // Select button for simulating user interaction
        const buttonEl = element.shadowRoot.querySelector('lightning-button');
        buttonEl.click();
        return Promise.resolve().then(() => {
            // Check if toast event has been fired
            expect(handler).toHaveBeenCalled();
            expect(handler.mock.calls[0][0].detail.title).toBe(TOAST_TITLE);
            expect(handler.mock.calls[0][0].detail.message).toBe(TOAST_MESSAGE);
            expect(handler.mock.calls[0][0].detail.variant).toBe(TOAST_VARIANT);
        });
    });
});

Also found above code in Tech Shorts Git repo

Labels:
LWC
Join the conversation