I'm on my first day of writing Jest tests for one of our LWCs, and that component fires an event with some dates included as the event detail
:
@api get selectedDates() {
return this.selectedSortedDates();
}
handleClick() {
let afterDates = this.selectedSortedDates();
const event = new CustomEvent('selectionchange', { detail: afterDates });
this.dispatchEvent(event);
}
This test code (inspired by How to test LWC onsuccess event handler in Jest) works:
const handler = jest.fn();
element.addEventListener('selectionchange', handler);
const tueJan28 = element.shadowRoot.querySelector('span[data-day="7331"]');
tueJan28.click();
const friJan31 = element.shadowRoot.querySelector('span[data-day="7344"]');
monFeb10.click();
// Can check the dates property
const expecteds = [
new Date(2020, 0, 28), // Tue
new Date(2020, 0, 29),
new Date(2020, 0, 30),
new Date(2020, 0, 31), // Fri
];
expect(element.selectedDates).toStrictEqual(expecteds);
return Promise.resolve().then(() => {
expect(handler).toHaveBeenCalledTimes(2);
// But how to check the event detail here?
// expect(handler).toHaveBeenCalledWith(... expecteds ...);
});
but I haven't managed to come up with a toHaveBeenCalledWith
technique that checks the event detail.
expect(handler).toHaveBeenCalledWith
says this is received:
{"composed": false, "isTrusted": false, "stopImmediatePropagation":
[Function value], "stopPropagation": [Function value]}
Is there a way capture the detail
of the event and assert its value?
Best Answer
This Jest Test Patterns and Mock Dependencies includes the answer:
where the mock property holds the information on the calls made with the first index the call number and the second index the argument number for that call.