3

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?

2

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}
}));
1
  • There is a slight grammar issue in your code which I fixed at my end. But generally speaking it works perfect. Thanks for that. – Lance Shi Jan 19 at 11:27

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.