2

I'm looking for help writing jest test for my onsuccess event handler for my lightning-record-edit form.

I'm new to jest so forgive me if this is covered somewhere else, I just haven't been able to find it on my own.

Below are snippets from my code, I had to re-write and generalize it, so please forgive any spelling mistakes.

html:

<template>
    <lighting-record-edit-form record-id={recordId} onsuccess={handleSuccess}>
        ...
        <lightning-button variant="brand" type="submit" label="Submit"></lightning-button>
    </lightning-record-edit-form>
</template>

js:

handleSuccess() {
    const event = new CustomEvent('formsaved');
    this.dispatchEvent(event);
}

test.js:

var element = createElement('c-test-component', {is: TestComponent});
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('formsaved', handler);

const btn = element.shadowRoot.querySelector('lightning-button');
btn.click();

return Promise.resolve().then(() => {
    expect(handler).toHaveBeenCalled();
});

It fails saying the mock function was not called. I have similar handlers for onsubmit and onerror as well.

  • Also, I also tried submitting the form instead of clicking the button and that didn't work either. const form = element.shadowRoot.querySelector('lightning-record-edit-form'); form.submit(); – aaron May 1 at 20:02
  • 2
    That won't work. lightning-record-edit-form has only a basic mock implementation. github.com/salesforce/lwc-jest/blob/master/src/lightning-mocks/… Not sure what you want to test. If you've functionality that depends on listening to a formsaved event you've to fire the event yourself. – muenzpraeger May 2 at 5:20
4

The comment from @muenzpraeger was correct. The event handler won't fire on its own, so it needs to be fired directly from the test.

So the test.js would look something like this:

var element = createElement('c-test-component', {is: TestComponent});
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('formsaved', handler);

const form = element.shadowRoot.querySelector('lightning-record-edit-form');
form.dispatchEvent(new CustomEvent('success');

return Promise.resolve().then(() => {
    expect(handler).toHaveBeenCalled();
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.