Files
heroui-vue/tests/form.test.ts
T
maoyingjie 53e76f676d fix(demos): restore form, overlay and toast demos to the pinned cn baseline
HD-02 scope, all against heroui ce90ea3 cn sources:

- card: add the text-primary class to the coin icons (source parity);
  card-with-form drops the added required validation and inline business
  note, restores the plain href="#" forgot-password link and the baseline
  alert("表单提交成功!") submit feedback (autocomplete kept: no visible
  impact, allowed by the task card)
- input-group-with-textarea: restore the four Tooltips and the Enter Kbd
  hint; drop the stale "Tooltip 组件尚未迁移" note from input-group.md
- alert-dialog: restore the h-px top light line in custom-styles and the
  truncated/missing description text in sizes/custom-portal/
  custom-animations (+ controlled); align the fluid-slide icon with the
  modal mapping (IconArrowBarUp for gravity-ui:arrow-up-from-line)
- toast: restore the upstream demo layout shells (variants/simple/
  custom-indicator/custom-queue) and the action button default variant:
  ToastActionButton now falls back to the Button defaults (primary/md)
  like upstream ToastActionButton, so variants' actions render primary,
  danger stays danger and default stays tertiary; toast.md defaults fixed
- submit demos: restore baseline feedback and structure — alert() for
  card/fieldset/form/checkbox/checkbox-group/switch/select/combo-box/
  autocomplete and console.log for search/number/time field form examples;
  modal-with-form returns to the close-only footer (no submit/result row);
  drop the added inline status/result rows and the max-w-full/
  max-sm:min-w-0 width guards from the restored demos
- radio-group-validation: add the missing text-muted to the result line;
  label.md invalid example gives the real control its invalid state and
  matches the baseline input shape

Tests re-pinned to the baseline contracts (alert/console/close behavior,
four tooltips + Kbd, positional modal footer); full suite 110 files /
1617 tests, typecheck, build:docs and the m35-m36 tarball contract pass.
2026-10-28 14:10:10 +08:00

313 lines
11 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Form,
TextField,
Input,
FieldError,
CheckboxGroup,
Switch,
} from "../packages/vue/src";
import FormBasic from "../apps/docs/demos/form-basic.vue";
import FormRenderFunction from "../apps/docs/demos/form-render-function.vue";
import FormCustomStyles from "../apps/docs/demos/form-custom-styles.vue";
const wrappers: ReturnType<typeof mount>[] = [];
// Submit occurs after mounting, as with real user input. Keep Vue's listener
// timestamp guard deterministic without changing private event properties.
beforeEach(() => vi.useFakeTimers({ toFake: ["Date"] }));
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
vi.useRealTimers();
});
function render(content: () => unknown, attrs: Record<string, unknown> = {}) {
const w = mount(Form, {
attrs,
slots: { default: content as () => ReturnType<typeof h> },
attachTo: document.body,
});
wrappers.push(w);
return w;
}
function submit(form: HTMLFormElement, submitter?: HTMLButtonElement) {
vi.setSystemTime(Date.now() + 1);
const event = new SubmitEvent("submit", {
bubbles: true,
cancelable: true,
submitter,
});
form.dispatchEvent(event);
return event;
}
const settle = async () => {
await nextTick();
await nextTick();
};
describe("Form public validation", () => {
it.each(["", "true", "false", true, false])(
"uses native boolean-attribute semantics for novalidate=%s",
(value) => {
const submitted = vi.fn((event: Event) => event.preventDefault());
const w = render(() => h("input", { required: true }), {
novalidate: value,
onSubmit: submitted,
});
submit(w.element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(value === false ? 0 : 1);
},
);
it.each([
() => h(CheckboxGroup, { isRequired: true }),
() => h(Switch, { isRequired: true }),
])(
"cancels composite focus and preserves the first invalid field across mixed controls",
async (Control) => {
const w = render(() => [h("input", { required: true }), Control()]);
submit(w.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
w.unmount();
wrappers.splice(wrappers.indexOf(w), 1);
const canceled = render(() => [Control(), h("button", "anchor")], {
onInvalid: (e: Event) => e.preventDefault(),
});
const button = canceled.get("button").element as HTMLButtonElement;
button.focus();
submit(canceled.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(button);
canceled.vm.checkValidity();
await settle();
expect(document.activeElement).toBe(button);
},
);
it("notifies once per invalid control and allows canceling default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const submitted = vi.fn();
const w = render(
() => [
h("input", { required: true, name: "one" }),
h("input", { required: true, name: "two" }),
h("button", { type: "submit" }, "submit"),
],
{ onInvalid: invalid, onSubmit: submitted },
);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
const event = submit(w.element as HTMLFormElement, button);
await settle();
expect(event.defaultPrevented).toBe(true);
expect(submitted).not.toHaveBeenCalled();
expect(invalid).toHaveBeenCalledTimes(2);
expect(invalid.mock.calls[0][0].target).toBe(w.get("input").element);
expect(document.activeElement).toBe(button);
});
it("focuses the first invalid control and updates associated field errors", async () => {
const invalid = vi.fn();
const w = render(
() => [
h(TextField, { name: "email", isRequired: true }, () => [
h(Input),
h(FieldError),
]),
h("input", { required: true, name: "second" }),
],
{ onInvalid: invalid },
);
await settle();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
expect(invalid).toHaveBeenCalledTimes(2);
expect(w.get("input").attributes("aria-describedby")).toContain(
w.get("[data-slot=field-error]").attributes("id"),
);
});
it("honors invalid cancellation on the field itself", async () => {
const w = render(() => [
h("input", {
required: true,
onInvalid: (e: Event) => e.preventDefault(),
}),
h("button", "anchor"),
]);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
expect(document.activeElement).toBe(button);
});
it("validates externally associated controls and can cancel their default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const w = mount(
defineComponent({
render: () =>
h("div", [
h(Form, { id: "external-form", onInvalid: invalid }),
h("input", { form: "external-form", required: true }),
h("button", "anchor"),
]),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(
submit(w.get("form").element as HTMLFormElement).defaultPrevented,
).toBe(true);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(button);
});
it("skips validation for formnovalidate and respects canceled submission/reset", async () => {
const invalid = vi.fn();
const submitted = vi.fn((event: Event) => event.preventDefault());
const reset = vi.fn((event: Event) => event.preventDefault());
const w = render(
() => [
h(Input, { name: "value", defaultValue: "initial", required: true }),
h("button", { formnovalidate: true, type: "submit" }, "skip"),
],
{ onInvalid: invalid, onSubmit: submitted, onReset: reset },
);
await w.get("input").setValue("");
const event = submit(
w.element as HTMLFormElement,
w.get("button").element as HTMLButtonElement,
);
expect(event.defaultPrevented).toBe(true);
expect(submitted).toHaveBeenCalledTimes(1);
expect(invalid).not.toHaveBeenCalled();
(w.element as HTMLFormElement).reset();
await settle();
expect(reset).toHaveBeenCalledTimes(1);
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("exposes native form access and policy-aware validation without duplicate invalid events", async () => {
const invalid = vi.fn();
const w = render(() => h("input", { name: "value", required: true }), {
onInvalid: invalid,
});
expect(w.vm.element).toBe(w.element);
expect(w.vm.checkValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.mockClear();
expect(w.vm.reportValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("valid");
expect(w.vm.checkValidity()).toBe(true);
w.vm.reset();
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("keeps dynamic native attrs and policy overrides on the real form", async () => {
const method = ref("post");
const submitted = vi.fn();
const w = mount(
defineComponent({
setup: () => () =>
h(
Form,
{
action: "/submit",
method: method.value,
validationBehavior: "aria",
onSubmit: submitted,
"data-custom": "foo",
},
() => h("input", { required: true }),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.get("form").attributes("action")).toBe("/submit");
expect(w.get("form").attributes("data-custom")).toBe("foo");
method.value = "get";
await settle();
expect(w.get("form").attributes("method")).toBe("get");
submit(w.get("form").element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(1);
});
});
describe("Form fixed-source demos", () => {
it.each([FormBasic, FormRenderFunction])(
"validates both fields, submits exact data via the baseline alert, and resets values/errors",
async (Demo) => {
const alert = vi.spyOn(window, "alert").mockImplementation(() => {});
const w = mount(Demo, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
await settle();
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(w.findAll("[data-slot=field-error]")).toHaveLength(2);
const email = w.get('input[name="email"]');
const password = w.get('input[name="password"]');
expect(document.activeElement).toBe(email.element);
expect(w.get("[data-slot=field-error]").text()).toBe(
"请输入有效的邮箱地址",
);
await email.setValue("john@example.com");
for (const [value, error] of [
["short", "密码至少需要 8 个字符"],
["lowercase1", "密码至少需要包含一个大写字母"],
["Password", "密码至少需要包含一个数字"],
]) {
await password.setValue(value);
await settle();
submit(form);
await settle();
expect(w.get("[data-slot=field-error]").text()).toBe(error);
expect(alert).not.toHaveBeenCalled();
}
await password.setValue("Password1");
await settle();
submit(form);
await settle();
expect(alert).toHaveBeenCalledTimes(1);
const message = alert.mock.calls[0][0] as string;
expect(message).toContain("表单提交数据:");
expect(message).toContain('"email": "john@example.com"');
expect(message).toContain('"password": "Password1"');
expect([...new FormData(form)]).toEqual([
["email", "john@example.com"],
["password", "Password1"],
]);
form.reset();
await settle();
expect((email.element as HTMLInputElement).value).toBe("");
expect((password.element as HTMLInputElement).value).toBe("");
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
if (Demo === FormRenderFunction) expect(form.dataset.custom).toBe("foo");
alert.mockRestore();
},
);
it("keeps the custom-styles example as a native validated form", async () => {
const w = mount(FormCustomStyles, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
expect(w.get("label").text()).toBe("工作邮箱");
expect(w.get("button").text()).toBe("继续");
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("you@company.com");
await settle();
expect(form.checkValidity()).toBe(true);
expect(submit(form).defaultPrevented).toBe(true);
expect([...new FormData(form)]).toEqual([["email", "you@company.com"]]);
});
});