I’m trying to unit test this component.
<template>
<form @submit.prevent="handleSubmit">
<div>
<ion-input
label="Email"
data-testid="email-input"
name="email"
label-placement="floating"
fill="solid"
v-model="form.email"
type="email"
required
/>
</div>
<div>
<label for="username">Username</label>
<input
id="username"
name="username"
v-model="form.username"
type="text"
required
/>
</div>
<div>
<label for="password">Password</label>
<input
id="password"
name="password"
v-model="form.password"
type="password"
required
/>
</div>
<ion-button type="submit" :disabled="isSubmitting">
{{ isSubmitting ? "Saving..." : "Submit" }}
</ion-button>
</form>
</template>
<script setup lang="ts">
import { IonInput, IonButton } from "@ionic/vue";
import { reactive, ref, watch } from "vue";
interface UserFormData {
email: string;
username: string;
password: string;
}
const props = defineProps<{
user?: Partial<UserFormData>;
saving: boolean;
}>();
const emit = defineEmits<{
(e: "submit", data: UserFormData): void;
}>();
const defaultUser: UserFormData = {
email: "",
username: "",
password: "",
};
const initialState = (): UserFormData => ({
...defaultUser,
...props.user,
});
const form = reactive<UserFormData>(initialState());
const isSubmitting = ref(false);
function handleSubmit() {
isSubmitting.value = true;
emit("submit", { ...form });
}
function resetForm() {
Object.assign(form, initialState());
}
watch(
() => props.saving,
(newVal, oldVal) => {
if (oldVal && !newVal) {
isSubmitting.value = false;
}
}
);
watch(
() => props.user,
() => {
Object.assign(form, initialState());
}
);
defineExpose({ resetForm });
</script>
For some reason, the click event is not triggering on the ion-button
:
import { mount } from "@vue/test-utils";
import { describe, expect, it } from "vitest";
import UserForm from "@/components/UserForm.vue";
describe("UserForm.vue", () => {
it("submits the form", async () => {
const wrapper = mount(UserForm, { props: { saving: false }, attachTo: document.body });
await wrapper.findComponent("[data-testid=email-input]").setValue("email@example.com");
await wrapper.find("input[name=username]").setValue("username");
await wrapper.find("input[name=password]").setValue("passwordf");
const submitButton = wrapper.findComponent("ion-button");
await submitButton.trigger("click");
expect(wrapper.emitted()).toHaveProperty("submit");
expect(submitButton.attributes("disabled")).toBeDefined();
wrapper.unmount();
});
});
expected { input: [ [ …(1) ], [ …(1) ] ], …(2) } to have property "submit"
Using the native <button>
the test passes, but with <ion-button>
it fails.
How do I properly manually trigger the click
event?