Search code examples
jestjssalesforce-lightninglwc

How to write the jest test for onclick event im salesforce lwc


I have below code. How can i cover in the Jest salesforce?

testhandle(event) {
        let testAbr = event.target.text;
        if (testAbr) {
            this.dispatchEvent(new CustomEvent('testpasss', { detail: { type: 'specilsnumber', input: testAbr } }));
        }
    }
    
    

this is coming on the click of user from UI. onclick={testhandle}


Solution

  • you can do a query of the markup element on which you have added the onclick handler method, and then dispatch a custom event on that element.

    Example:

    element.shadowRoot.querySelector('.hasOnclick').dispatchEvent(new CustomEvent('click'));
    

    Make sure to add test assert in promise.resolve() to handle asynchronous DOM updates as below:

    return Promise.resolve().then(() => {
          expect(value).toBe(expected);
    });