9

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.

2
  • 1
    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, 2019 at 20:02
  • 3
    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. May 2, 2019 at 5:20

1 Answer 1

12

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();
});
1
  • form.dispatchEvent... line needs an extra closing bracket but 'edits must be at least 6 characters' so I can't make the edit directly :-)
    – MikeA
    Apr 28, 2023 at 16:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .