Files
heroui-vue/tests/choice-fields.test.ts
T

627 lines
20 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
CheckboxGroup,
Radio,
RadioContent,
RadioControl,
RadioIndicator,
RadioGroup,
Description,
FieldError,
Fieldset,
FieldsetLegend,
Form,
Label,
} from "../packages/vue/src";
const tick = async () => {
await nextTick();
await nextTick();
};
afterEach(() => {
document.body.innerHTML = "";
});
function option(
kind: "checkbox" | "radio",
value: string,
props: Record<string, unknown> = {},
) {
return h(kind === "checkbox" ? Checkbox : Radio, { value, ...props }, () => [
h(kind === "checkbox" ? CheckboxContent : RadioContent, {}, () => [
h(kind === "checkbox" ? CheckboxControl : RadioControl, {}, () =>
h(kind === "checkbox" ? CheckboxIndicator : RadioIndicator),
),
h(Label, {}, () => value),
]),
h(Description, {}, () => `${value} hint`),
]);
}
function group(
kind: "checkbox" | "radio",
props: Record<string, unknown> = {},
options: Record<string, unknown>[] = [{}, {}, {}],
) {
const children = () => [
h(Label, {}, () => "Choices"),
h(Description, {}, () => "Group hint"),
...options.map((props, index) =>
option(kind, ["a", "b", "c"][index], props),
),
h(FieldError),
];
return kind === "checkbox"
? h(CheckboxGroup, props, children)
: h(RadioGroup, props, children);
}
function inForm(
content: () => ReturnType<typeof h>,
props: Record<string, unknown> = {},
) {
return defineComponent({ render: () => h(Form, props, content) });
}
const formData = (w: ReturnType<typeof mount>) =>
Array.from(new FormData(w.get("form").element as HTMLFormElement));
const inputs = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLInputElement>("input[data-choice-input]");
describe("Checkbox native value protocol", () => {
it("keeps explicit composition, native semantics, default indicators and sibling descriptions", async () => {
const w = mount(option("checkbox", "a"));
await tick();
expect(w.find("label.hv-checkbox__content").exists()).toBe(true);
expect(inputs(w)[0].attributes("type")).toBe("checkbox");
expect(w.get("[data-slot=label]").element.tagName).toBe("SPAN");
expect(
w.find("[data-slot=checkbox-default-indicator--checkmark]").exists(),
).toBe(true);
const ref = inputs(w)[0].attributes("aria-describedby")!;
expect(w.get(`[id="${ref}"]`).text()).toBe("a hint");
w.unmount();
});
it("submits exactly one native value only when selected, and resets to initial selection", async () => {
const change = vi.fn();
const w = mount(
inForm(() =>
option("checkbox", "yes", {
name: "ok",
defaultChecked: true,
"onUpdate:checked": change,
}),
),
{ attachTo: document.body },
);
expect(formData(w)).toEqual([["ok", "yes"]]);
await inputs(w)[0].setValue(false);
expect(formData(w)).toEqual([]);
expect(change).toHaveBeenCalledExactlyOnceWith(false);
(w.get("form").element as HTMLFormElement).reset();
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(formData(w)).toEqual([["ok", "yes"]]);
w.unmount();
});
it("restores controlled rejection and honors canceled reset", async () => {
const change = vi.fn();
const w = mount(
inForm(() =>
option("checkbox", "yes", {
checked: true,
"onUpdate:checked": change,
}),
),
{ attachTo: document.body },
);
await inputs(w)[0].setValue(false);
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(change).toHaveBeenCalledExactlyOnceWith(false);
w.unmount();
const u = mount(
inForm(() => option("checkbox", "a")),
{ attachTo: document.body },
);
await inputs(u)[0].setValue(true);
const form = u.get("form").element as HTMLFormElement;
form.addEventListener("reset", (e) => e.preventDefault());
form.reset();
await tick();
expect(inputs(u)[0].element.checked).toBe(true);
u.unmount();
});
it("separates mixed appearance from the actual submitted boolean", async () => {
const w = mount(
inForm(() =>
option("checkbox", "yes", { name: "mixed", isIndeterminate: true }),
),
{ attachTo: document.body },
);
await tick();
expect(inputs(w)[0].element.indeterminate).toBe(true);
expect(formData(w)).toEqual([]);
expect(
w.find("[data-slot=checkbox-default-indicator--indeterminate]").exists(),
).toBe(true);
w.unmount();
});
it("blocks readonly pointer and keyboard changes without disabling focus", async () => {
const change = vi.fn();
const w = mount(
option("checkbox", "a", {
isReadOnly: true,
checked: true,
"onUpdate:checked": change,
}),
{ attachTo: document.body },
);
const input = inputs(w)[0];
await input.trigger("click");
await input.trigger("keydown", { key: " " });
await tick();
expect(change).not.toHaveBeenCalled();
expect(input.element.checked).toBe(true);
expect(input.attributes("disabled")).toBeUndefined();
input.element.focus();
expect(document.activeElement).toBe(input.element);
w.unmount();
});
it("routes an external Label for to the actual checkbox", async () => {
const w = mount(
defineComponent({
render: () =>
h("div", {}, [
option("checkbox", "a", { id: "external" }),
h(Label, { for: "external" }, () => "External"),
]),
}),
);
expect(inputs(w)[0].attributes("id")).toBe("external");
expect(w.get("label[for=external]").text()).toBe("External");
w.unmount();
});
});
for (const kind of ["checkbox", "radio"] as const) {
describe(`${kind} group`, () => {
it("uses repeated plain names or a single selected scalar, without hidden duplicate values", async () => {
const w = mount(
inForm(() =>
group(kind, {
name: "choices",
defaultValue: kind === "checkbox" ? ["a", "b"] : "b",
}),
),
{ attachTo: document.body },
);
await tick();
expect(formData(w)).toEqual(
kind === "checkbox"
? [
["choices", "a"],
["choices", "b"],
]
: [["choices", "b"]],
);
expect(w.find("input[name='choices[0]']").exists()).toBe(false);
w.unmount();
});
it("omits group, member and Fieldset disabled values and preserves first legend exemption", async () => {
const off = ref(true);
const w = mount(
inForm(() =>
h(Fieldset, { disabled: off.value }, () => [
h(FieldsetLegend, {}, () =>
option("checkbox", "legend", {
name: "legend",
defaultChecked: true,
}),
),
group(
kind,
{
name: "choices",
defaultValue: kind === "checkbox" ? ["a", "b"] : "b",
},
[{}, { isDisabled: true }, {}],
),
]),
),
{ attachTo: document.body },
);
await tick();
expect(formData(w)).toEqual([["legend", "legend"]]);
off.value = false;
await tick();
expect(formData(w)).toEqual(
kind === "checkbox"
? [
["legend", "legend"],
["choices", "a"],
]
: [["legend", "legend"]],
);
w.unmount();
});
it("restores initial values on reset, preserves controlled values and canceled resets", async () => {
const initial = kind === "checkbox" ? ["a"] : "a";
const w = mount(
inForm(() => group(kind, { name: "choice", defaultValue: initial })),
{ attachTo: document.body },
);
await inputs(w)[1].setValue(true);
await tick();
const form = w.get("form").element as HTMLFormElement;
form.reset();
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
await inputs(w)[1].setValue(true);
form.addEventListener("reset", (e) => e.preventDefault());
const before = formData(w);
form.reset();
await tick();
expect(formData(w)).toEqual(before);
w.unmount();
const change = vi.fn();
const controlled = mount(
inForm(() =>
group(kind, {
name: "choice",
modelValue: initial,
"onUpdate:modelValue": change,
}),
),
{ attachTo: document.body },
);
await inputs(controlled)[1].setValue(true);
await tick();
expect(formData(controlled)).toEqual([["choice", "a"]]);
expect(change).toHaveBeenCalledTimes(1);
(controlled.get("form").element as HTMLFormElement).reset();
await tick();
expect(formData(controlled)).toEqual([["choice", "a"]]);
controlled.unmount();
});
it("validates one group constraint, displays errors and focuses a visible available choice", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() =>
group(kind, { name: "required", isRequired: true }, [
{ isDisabled: true },
{},
{},
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).not.toHaveBeenCalled();
expect(w.get("[data-slot=field-error]").text()).toContain("请选择");
expect(document.activeElement).toBe(inputs(w)[1].element);
await inputs(w)[2].setValue(true);
await tick();
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).toHaveBeenCalledOnce();
expect(formData(w)).toEqual([["required", "c"]]);
w.unmount();
});
it("honors aria validation, readonly and an empty group without a focusable member", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() => group(kind, { isRequired: true, validationBehavior: "aria" }),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
await tick();
(w.get("form").element as HTMLFormElement).requestSubmit();
expect(submit).toHaveBeenCalledOnce();
expect(w.get("[data-slot=field-error]").text()).toContain("请选择");
w.unmount();
const empty = mount(
inForm(() => group(kind, { isRequired: true }, [])),
{ attachTo: document.body },
);
(empty.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(document.activeElement).toBe(
empty.get(`[data-slot=${kind}-group]`).element,
);
empty.unmount();
const change = vi.fn();
const ro = mount(
group(kind, {
isReadOnly: true,
defaultValue: kind === "checkbox" ? ["a"] : "a",
"onUpdate:modelValue": change,
}),
{ attachTo: document.body },
);
await inputs(ro)[1].trigger("click");
await inputs(ro)[0].trigger("keydown", { key: "ArrowDown" });
expect(change).not.toHaveBeenCalled();
ro.unmount();
});
it("uses group label IDs and isolates item descriptions from group descriptions", async () => {
const w = mount(group(kind));
await tick();
const root = w.get(`[data-slot=${kind}-group]`);
const groupLabel = w.get(`[id="${root.attributes("aria-labelledby")}"]`);
expect(groupLabel.element.tagName).toBe("SPAN");
expect(groupLabel.text()).toBe("Choices");
const first = inputs(w)[0].attributes("aria-describedby")!.split(" ");
const second = inputs(w)[1].attributes("aria-describedby")!.split(" ");
expect(first).toContain(root.attributes("aria-describedby"));
expect(first.filter((id) => !second.includes(id))).toHaveLength(1);
w.unmount();
});
it("rebinds external form association and a dynamic name, including reset ownership", async () => {
const form = ref("one"),
name = ref("old");
const w = mount(
defineComponent({
render: () =>
h("div", {}, [
h("form", { id: "one" }),
h("form", { id: "two" }),
group(kind, {
form: form.value,
name: name.value,
defaultValue: kind === "checkbox" ? ["a"] : "a",
}),
]),
}),
{ attachTo: document.body },
);
await tick();
form.value = "two";
name.value = "new";
await tick();
await inputs(w)[1].setValue(true);
await tick();
const one = w.get("#one").element as HTMLFormElement,
two = w.get("#two").element as HTMLFormElement;
expect(Array.from(new FormData(one))).toEqual([]);
expect(new FormData(two).getAll("new")).toEqual(
kind === "checkbox" ? ["a", "b"] : ["b"],
);
one.reset();
await tick();
expect(inputs(w)[1].element.checked).toBe(true);
two.reset();
await tick();
expect(new FormData(two).getAll("new")).toEqual(["a"]);
w.unmount();
});
});
}
it("handles radio arrows, RTL, disabled skipping and caller cancellation", async () => {
const w = mount(
group("radio", { defaultValue: "a", dir: "rtl" }, [
{},
{ isDisabled: true },
{},
]),
{ attachTo: document.body },
);
await tick();
expect(inputs(w).map((x) => x.attributes("tabindex"))).toEqual([
"0",
"-1",
"-1",
]);
await inputs(w)[0].trigger("keydown", { key: "ArrowLeft" });
await tick();
expect(inputs(w)[2].element.checked).toBe(true);
expect(document.activeElement).toBe(inputs(w)[2].element);
await inputs(w)[2].trigger("keydown", { key: "Home" });
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
w.unmount();
const change = vi.fn();
const canceled = mount(
group("radio", {
defaultValue: "a",
"onUpdate:modelValue": change,
onKeydown: (e: Event) => e.preventDefault(),
}),
);
await tick();
await inputs(canceled)[0].trigger("keydown", { key: "ArrowDown" });
expect(change).not.toHaveBeenCalled();
canceled.unmount();
});
it("preserves dynamic slots, selection and classes when members reorder or disappear", async () => {
const values = ref(["a", "b", "c"]),
variant = ref<"primary" | "secondary">("primary");
const w = mount(
inForm(() =>
h(
CheckboxGroup,
{ name: "choices", defaultValue: ["b"], variant: variant.value },
() => [
h(Label, {}, () => "Options"),
...values.value.map((value) =>
h(Checkbox, { key: value, value, class: { custom: true } }, () =>
h(CheckboxContent, {}, () => value),
),
),
],
),
),
{ attachTo: document.body },
);
values.value = ["c", "b", "a"];
variant.value = "secondary";
await tick();
expect(formData(w)).toEqual([["choices", "b"]]);
expect(w.get("[data-slot=checkbox]").classes()).toContain(
"hv-checkbox--secondary",
);
values.value = ["a", "c"];
await tick();
expect(formData(w)).toEqual([]);
values.value = ["b", "a"];
await tick();
expect(formData(w)).toEqual([["choices", "b"]]);
w.unmount();
});
it("clears the current server errors on edit and accepts a replacement response", async () => {
const errors = ref<Record<string, string | string[]>>({
choice: ["First error", "Second error"],
});
const w = mount(
{
render: () =>
h(Form, { validationErrors: errors.value }, () =>
group("checkbox", { name: "choice" }),
),
},
{ attachTo: document.body },
);
await tick();
expect(w.get("[data-slot=field-error]").text()).toContain("First error");
await inputs(w)[0].setValue(true);
await tick();
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
errors.value = { choice: "Replacement error" };
await tick();
expect(w.get("[data-slot=field-error]").text()).toBe("Replacement error");
w.unmount();
});
it("shows standalone native validation and allows aria override on grouped members", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() =>
h(Checkbox, { isRequired: true, name: "terms" }, () => [
h(CheckboxContent, {}, () => "Terms"),
h(FieldError),
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).not.toHaveBeenCalled();
expect(w.get("[data-slot=field-error]").text()).toBe("请选择此选项。");
expect(document.activeElement).toBe(inputs(w)[0].element);
w.unmount();
const aria = mount(
inForm(
() =>
group("checkbox", { validationBehavior: "aria" }, [
{ isRequired: true },
{},
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
await tick();
(aria.get("form").element as HTMLFormElement).requestSubmit();
expect(submit).toHaveBeenCalledOnce();
aria.unmount();
});
it("removes stale group label IDs and old attrs/events when parents update", async () => {
const attrs = ref<Record<string, unknown>>({}),
id = ref("label-one"),
handler = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(CheckboxGroup, attrs.value, () => [
h(Label, { id: id.value }, () => "Group"),
option("checkbox", "a"),
]),
}),
);
attrs.value = {
class: ["custom", { more: true }],
"aria-label": "Accessible",
"onUpdate:modelValue": handler,
};
id.value = "label-two";
await tick();
expect(
w.get('[data-slot="checkbox-group"]').attributes("aria-labelledby"),
).toBe("label-two");
expect(w.classes()).toContain("more");
await inputs(w)[0].setValue(true);
expect(handler).toHaveBeenCalledOnce();
attrs.value = {};
await tick();
await inputs(w)[0].setValue(false);
expect(handler).toHaveBeenCalledOnce();
expect(w.classes()).not.toContain("custom");
expect(w.attributes("aria-label")).toBeUndefined();
attrs.value = { "aria-label": "Again" };
await tick();
expect(w.attributes("aria-label")).toBe("Again");
w.unmount();
});
it("honors the defaultSelected alias unless defaultChecked is explicitly provided", async () => {
const w = mount(
inForm(() =>
h("div", {}, [
option("checkbox", "a", { name: "choices", defaultSelected: true }),
option("checkbox", "b", {
name: "choices",
defaultSelected: true,
defaultChecked: false,
}),
]),
),
);
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(inputs(w)[1].element.checked).toBe(false);
expect(formData(w)).toEqual([["choices", "a"]]);
w.unmount();
});
it("switches control ownership even when a newly present model is explicitly undefined", async () => {
const attrs = ref<Record<string, unknown>>({
defaultChecked: true,
name: "choice",
});
const w = mount(inForm(() => option("checkbox", "a", attrs.value)));
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
attrs.value = { ...attrs.value, checked: undefined };
await tick();
expect(formData(w)).toEqual([]);
await inputs(w)[0].setValue(true);
await tick();
expect(inputs(w)[0].element.checked).toBe(false);
attrs.value = { defaultChecked: true, name: "choice" };
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
w.unmount();
});
it("keeps a readonly radio member unchanged when arrow navigation focuses it", async () => {
const w = mount(
inForm(() =>
group("radio", { defaultValue: "a" }, [{}, { isReadOnly: true }, {}]),
),
{ attachTo: document.body },
);
await tick();
await inputs(w)[0].trigger("keydown", { key: "ArrowDown" });
await tick();
expect(document.activeElement).toBe(inputs(w)[1].element);
expect(inputs(w)[0].element.checked).toBe(true);
expect(inputs(w)[1].element.checked).toBe(false);
w.unmount();
});