[SalesForce] lwc jest event.detail.value doesn’t seem to work very well with jest test

On lightning-input and lightning-combobox, if we use event.target.value in the on change event, it works fine with the jest test. However, when we use event.detail.value in the on change event, the jest test will be throwing an error saying cannot read property 'value' of null.

Sample lwc js code:

  handleStartDateChange(e) {
    this.startDate = e.detail.value;
  }

Sample jest code:

    const startDateInput = element.shadowRoot.querySelector('lightning-input[class="startDateInput"]');
    startDateInput.value = new Date().toISOString().slice(0, 10);
    startDateInput.dispatchEvent(new CustomEvent('change'));

Event.target and Event.detail seem to be work both fine for us in actual code so we have used them interchangeably in our current code base. But it seems that event.detail doesn't work very well with jest. Does that mean we need to change every event.detail into event.target in order to get the tests pass?

Best Answer

You are dispatching the custom event 'change' but that won't automatically have a detail associated with it. So event.detail is null in this case.

The custom event will have a target since you are calling it on the startDateInput.

I guess behind the scenes, when using it live, the lightning input is associating the detail with the value of the input field, but if you want to dispatch your own custom event, you'll have to make that association -

startDateInput.dispatchEvent(new CustomEvent('change', {
   detail: {value: startDateInput.value}
}));