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.
Best Answer
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: