I have an lwc component which validates some input fields before performing a post request to the server. I'm writing a unit test where I'm testing that the post request is called when all input fields are valid (required validation, max-length validation, min-length validation, etc.).
However, when debugging this unit test I noticed that the element's validity object is undefined causing the post request to not trigger.
This is the method that performs the post request:
postIdea() {
const allValid = [
...this.template.querySelectorAll(
".slds-form lightning-input, .slds-form lightning-combobox"
)
].reduce((validSoFar, inputCmp) => {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
if (allValid) {
createIdea({
heading: this.heading,
ideaBody: this.ideaBody,
category: this.selectedCategory,
zone: this.zone
}).then(response => {
if (response.isSuccess) {
this.resetForm();
this.postingIdea = !this.postingIdea;
} else {
this.hasErrors = true;
}
});
}
}
variable allValid is always undefined which causes this to misbehave when running the unit test. But it behaves ok when seeing the real thing in the browser.
This is the unit test I wrote:
it("should post idea and close modal", () => {
const element = createElement("c-post-idea", { is: PostIdea });
document.body.appendChild(element);
getCategoriesWireAdapter.emit(mockedCategories);
createIdea.mockResolvedValue({ isSucess: true });
return Promise.resolve()
.then(() => {
const button = element.shadowRoot.querySelector("lightning-button");
button.dispatchEvent(new CustomEvent("click"));
})
.then(() => {
const headingTextInput = element.shadowRoot.querySelector(
"lightning-input"
);
const categorySelectInput = element.shadowRoot.querySelector(
"lightning-combobox"
);
const descriptionRichText = element.shadowRoot.querySelector(
"lightning-input-rich-text"
);
headingTextInput.value = "this is a new idea";
headingTextInput.dispatchEvent(new CustomEvent("change"));
categorySelectInput.value = "bar";
categorySelectInput.dispatchEvent(new CustomEvent("change"));
descriptionRichText.value = "this is the description of my idea";
descriptionRichText.dispatchEvent(new CustomEvent("change"));
const postButton = element.shadowRoot.querySelector(
".post-idea-button"
);
postButton.dispatchEvent(new CustomEvent("click"));
})
.then(() => {
expect(createIdea).toHaveBeenCalled();
})
.then(() => {
const modal = element.shadowRoot.querySelector(".slds-modal");
expect(modal).toBeNull();
});
});