2

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?

2

This Jest Test Patterns and Mock Dependencies includes the answer:

    return Promise.resolve().then(() => {
        expect(handler).toHaveBeenCalledTimes(2);
        expect(handler.mock.calls[0][0].detail).toStrictEqual(click0Expecteds);
        expect(handler.mock.calls[1][0].detail).toStrictEqual(click1Expecteds);
    });

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.

| improve this answer | |

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.