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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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(); });
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0