import { afterEach, describe, expect, it, vi } from "vitest"; import { mount, flushPromises, DOMWrapper } from "@vue/test-utils"; import { defineComponent, ref } from "vue"; import { Modal, ModalBackdrop, ModalContainer, ModalDialog, ModalHeading, ModalBody, ModalTrigger, Button, Select, SelectTrigger, SelectValue, SelectClearButton, SelectIndicator, SelectPopover, ListBox, ListBoxItem, ListBoxItemIndicator, ListBoxSection, Label, Description, Header, FieldError, Fieldset, Form, } from "../packages/vue/src"; const components = { Modal, ModalBackdrop, ModalContainer, ModalDialog, ModalHeading, ModalBody, ModalTrigger, Button, Select, SelectTrigger, SelectValue, SelectClearButton, SelectIndicator, SelectPopover, ListBox, ListBoxItem, ListBoxItemIndicator, ListBoxSection, Label, Description, Header, FieldError, Fieldset, Form, }; const wrappers: ReturnType[] = []; afterEach(() => { wrappers.splice(0).forEach((w) => w.unmount()); document.body.innerHTML = ""; }); const options = 'DetailsDisabledLast'; const content = `Help${options}`; function fixture(template: string, setup = () => ({})) { const wrapper = mount(defineComponent({ components, setup, template }), { attachTo: document.body, }); wrappers.push(wrapper); return wrapper; } const trigger = (w: ReturnType) => w.get('[data-slot="select-trigger"]'); const option = (index: number) => document.querySelectorAll('[role="option"]')[index]; async function clickOption(index: number) { option(index).click(); await flushPromises(); } const data = () => [...new FormData(document.querySelector("form")!).entries()]; describe("Select public contracts", () => { it("plans closed labels and submits raw numeric/string keys once", async () => { const w = fixture( `
`, ); expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number"); expect(data()).toEqual([["choice", "0"]]); expect(document.querySelector('[role="listbox"]')).toBeNull(); await trigger(w).trigger("click"); await flushPromises(); expect(document.querySelector('[role="listbox"]')).not.toBeNull(); expect(option(0).getAttribute("aria-selected")).toBe("true"); await clickOption(1); expect( w.getComponent(components.Select).emitted("update:modelValue"), ).toEqual([["0"]]); expect(data()).toEqual([["choice", "0"]]); expect(w.get('[data-slot="select-value"]').text()).toBe("Zero string"); }); it("uses parent accepted multiple values, retries rejected proposals, and keeps the popup open", async () => { const value = ref<(string | number)[]>([0]); const w = fixture( `
`, () => ({ value }), ); await trigger(w).trigger("click"); await flushPromises(); await clickOption(1); await clickOption(1); expect( w.getComponent(components.Select).emitted("update:modelValue"), ).toEqual([[[0, "0"]], [[0, "0"]]]); expect(option(1).getAttribute("aria-selected")).toBe("false"); value.value = [0, "0"]; await flushPromises(); expect(data()).toEqual([ ["choice", "0"], ["choice", "0"], ]); expect(trigger(w).attributes("aria-expanded")).toBe("true"); }); it("clears without toggling, supports closed Delete only with a clear affordance", async () => { const w = fixture(``); await w .get('[data-slot="select-clear-button"]') .trigger("click", { button: 0 }); expect(trigger(w).attributes("aria-expanded")).toBe("false"); expect(w.getComponent(components.Select).emitted("clear")).toHaveLength(1); expect( w.getComponent(components.Select).emitted("update:modelValue"), ).toEqual([[null]]); const plain = fixture( ``, ); await trigger(plain).trigger("keydown", { key: "Delete" }); expect( plain.getComponent(components.Select).emitted("change"), ).toBeUndefined(); }); it("honors disabled/readonly state and native reset", async () => { const w = fixture( `
`, ); await trigger(w).trigger("keydown", { key: "Delete" }); expect(data()).toEqual([]); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(data()).toEqual([["choice", "last"]]); w.unmount(); wrappers.pop(); document.body.innerHTML = ""; const readonly = fixture( `
`, ); await trigger(readonly).trigger("click"); expect(trigger(readonly).attributes("aria-expanded")).toBe("false"); await trigger(readonly).trigger("keydown", { key: "Delete" }); expect(data()).toEqual([["choice", "last"]]); }); it("links field labels, descriptions and errors without option leakage", async () => { const w = fixture(``); const t = trigger(w); const ids = t.attributes("aria-labelledby")!.split(" "); expect( ids.map((id) => document.getElementById(id)?.textContent).join(" "), ).toContain("Choice"); expect(t.attributes("aria-describedby")).toBeTruthy(); expect( w.get('input[type="checkbox"]').element.checkValidity(), ).toBe(false); await flushPromises(); expect(t.attributes("aria-invalid")).toBe("true"); await t.trigger("click"); await flushPromises(); await clickOption(0); expect( w.get('input[type="checkbox"]').element.checkValidity(), ).toBe(true); expect(t.attributes("aria-labelledby")).toBe(ids.join(" ")); }); it("allows trigger event cancellation and honors explicit root accessible names", async () => { const w = fixture( ``, ); await trigger(w).trigger("click"); await flushPromises(); expect(trigger(w).attributes("aria-expanded")).toBe("false"); expect(trigger(w).attributes("aria-label")).toBe("Named"); }); }); describe("Select form and collection changes", () => { it("uses native autocomplete proposals and restores rejected parent values", async () => { const w = fixture( `
`, ); const native = w.get("select"); expect(native.attributes("autocomplete")).toBe("country"); native.element.selectedIndex = 2; await native.trigger("change"); await flushPromises(); expect(w.getComponent(Select).emitted("change")).toEqual([["0"]]); expect(native.element.selectedIndex).toBe(1); expect(data()).toEqual([["choice", "0"]]); }); it("omits removed or disabled selected options from FormData and constraints", async () => { const show = ref(true), disabled = ref(false); const w = fixture( `
`, () => ({ show, disabled }), ); expect(data()).toEqual([["choice", "a"]]); disabled.value = true; await flushPromises(); expect(data()).toEqual([]); disabled.value = false; await flushPromises(); expect(data()).toEqual([["choice", "a"]]); show.value = false; await flushPromises(); expect(data()).toEqual([]); }); it("omits Fieldset-disabled values and preserves readonly values", async () => { const w = fixture( `
`, ); expect(trigger(w).attributes("disabled")).toBeDefined(); expect(data()).toEqual([]); }); it("keeps controlled reset and cancelled reset without synthetic changes", async () => { const w = fixture( `
`, ); await trigger(w).trigger("keydown", { key: "Backspace" }); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(data()).toEqual([]); expect(w.getComponent(Select).emitted("change")).toEqual([[null]]); }); it("counts conditional clear affordances and honors actual trigger disabled state", async () => { const clear = ref(true), disabled = ref(true); const w = fixture( ``, () => ({ clear, disabled }), ); await w .get('[data-slot="select-clear-button"]') .trigger("click", { button: 0 }); expect(w.getComponent(Select).emitted("change")).toBeUndefined(); disabled.value = false; clear.value = false; await flushPromises(); await trigger(w).trigger("keydown", { key: "Delete" }); expect(w.getComponent(Select).emitted("change")).toBeUndefined(); clear.value = true; await flushPromises(); await trigger(w).trigger("keydown", { key: "Delete" }); expect(w.getComponent(Select).emitted("change")).toEqual([[null]]); }); it("keeps open controlled, retries rejected openings and respects explicit undefined precedence", async () => { const w = fixture( ``, ); expect(trigger(w).attributes("aria-expanded")).toBe("false"); await trigger(w).trigger("click"); await trigger(w).trigger("click"); expect(w.getComponent(Select).emitted("update:open")).toEqual([ [true], [true], ]); }); it("focuses the selected option on open and skips disabled items", async () => { const w = fixture(``); await trigger(w).trigger("keydown", { key: "ArrowDown" }); await flushPromises(); expect(document.activeElement).toBe(option(3)); option(3).dispatchEvent( new KeyboardEvent("keydown", { key: "Home", bubbles: true }), ); await flushPromises(); expect(document.activeElement).toBe(option(0)); }); }); describe("Select popup boundary", () => { it("uses a presentation popup and a named listbox with correct ARIA ownership", async () => { const w = fixture(``); await trigger(w).trigger("click"); await flushPromises(); const popup = document.querySelector('[data-slot="select-popover"]')!; expect(popup).not.toBeNull(); expect(popup.getAttribute("role")).toBe("presentation"); const list = document.querySelector('[role="listbox"]')!; expect(trigger(w).attributes("aria-controls")).toBe(list.id); expect(trigger(w).attributes("aria-haspopup")).toBe("listbox"); expect(list.getAttribute("aria-labelledby")).toBe( w.get('[data-slot="label"]').attributes("id"), ); }); it("leaves Tab default traversal at the trigger without looping in the portal", async () => { const w = fixture( `
`, ); await trigger(w).trigger("click"); await flushPromises(); const event = new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true, }); option(0).dispatchEvent(event); await flushPromises(); expect(event.defaultPrevented).toBe(false); expect(document.activeElement).toBe(trigger(w).element); expect(trigger(w).attributes("aria-expanded")).toBe("false"); }); it("keeps controlled native selected options on reset even when Vue props did not change", async () => { const value = ref("last"); const w = fixture( `
`, () => ({ value }), ); value.value = 0; await flushPromises(); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number"); expect(data()).toEqual([["choice", "0"]]); }); }); describe("Select names, cancellation and closed keyboard", () => { it("moves focus on field Label click without opening the menu", async () => { const w = fixture(``); await w.get('[data-slot="label"]').trigger("click"); expect(document.activeElement).toBe(trigger(w).element); expect(trigger(w).attributes("aria-expanded")).toBe("false"); }); it("supports closed typeahead and skips disabled options without editing during IME", async () => { const w = fixture( ``, ); for (const key of ["l", "i", "a", "m"]) await trigger(w).trigger("keydown", { key }); expect(w.get('[data-slot="select-value"]').text()).toBe("Liam Smith"); expect(w.getComponent(Select).emitted("change")).toEqual([["a"]]); await trigger(w).trigger("keydown", { key: "m", isComposing: true }); expect(w.getComponent(Select).emitted("change")).toHaveLength(1); expect(trigger(w).attributes("aria-expanded")).toBe("false"); }); it("respects ListBox activation cancellation before selection or closing", async () => { const w = fixture( ``, ); await trigger(w).trigger("click"); await flushPromises(); option(0).dispatchEvent( new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(w.getComponent(Select).emitted("change")).toBeUndefined(); expect(trigger(w).attributes("aria-expanded")).toBe("true"); }); it("keeps aria validation nonblocking and refreshes Form server errors", async () => { const errors = ref>({ choice: "Server error" }); const w = fixture( `
`, () => ({ errors }), ); expect(trigger(w).attributes("aria-invalid")).toBe("true"); expect(w.text()).toContain("Server error"); expect( w.get('input[type="checkbox"]').element.checkValidity(), ).toBe(true); await trigger(w).trigger("click"); await flushPromises(); await clickOption(0); expect(w.text()).not.toContain("Server error"); errors.value = { choice: "Refreshed" }; await flushPromises(); expect(w.text()).toContain("Refreshed"); }); }); describe("Select metadata and identity", () => { it("retains empty-string identities through native form submission", async () => { const w = fixture( `
`, ); expect(data()).toEqual([["choice", ""]]); expect(w.get('[data-slot="select-value"]').text()).toBe("Empty key"); await trigger(w).trigger("click"); await flushPromises(); expect(option(0).getAttribute("aria-selected")).toBe("true"); }); it("associates an external form dynamically and restores reset values", async () => { const owner = ref("one"); const w = fixture( `
`, () => ({ owner }), ); owner.value = "two"; await flushPromises(); await trigger(w).trigger("keydown", { key: "Delete" }); (w.get("#one").element as HTMLFormElement).reset(); await flushPromises(); expect( w.get('[data-slot="select-value"]').attributes("data-placeholder"), ).toBe("true"); (w.get("#two").element as HTMLFormElement).reset(); await flushPromises(); expect( new FormData(w.get("#two").element as HTMLFormElement).get("choice"), ).toBe("last"); }); it("refreshes explicit asynchronous selected metadata before opening", async () => { const items = ref<{ id: number; textValue: string }[]>([]); const w = fixture( `
`, () => ({ items }), ); expect(data()).toEqual([]); items.value = [{ id: 0, textValue: "Loaded label" }]; await flushPromises(); expect(w.get('[data-slot="select-value"]').text()).toBe("Loaded label"); expect(data()).toEqual([["choice", "0"]]); items.value = []; await flushPromises(); expect(data()).toEqual([]); }); it("gives root accessible names to the popup list and keeps cancellation intact", async () => { const w = fixture(``); await trigger(w).trigger("click"); await flushPromises(); expect( document.querySelector('[role="listbox"]')?.getAttribute("aria-label"), ).toBe("Root name"); }); }); describe("Select integration boundaries", () => { it("keeps a nested Modal open when its Select handles Escape", async () => { const w = fixture( `Open modalParent dialog`, ); await w.get('[data-slot="modal-trigger"]').trigger("click"); await flushPromises(); const selectTrigger = document.querySelector( '[data-slot="select-trigger"]', )!; selectTrigger.click(); await flushPromises(); expect(option(0)).toBeTruthy(); option(0).dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); expect(selectTrigger.getAttribute("aria-expanded")).toBe("false"); }); it("honors open autofocus cancellation and native handler array stop semantics", async () => { const calls: string[] = []; const stop = (event: Event) => { calls.push("first"); event.stopImmediatePropagation(); }; const second = () => calls.push("second"); const w = fixture( ``, () => ({ stop, second }), ); await trigger(w).trigger("keydown", { key: "ArrowDown" }); expect(calls).toEqual(["first"]); expect(trigger(w).attributes("aria-expanded")).toBe("false"); (trigger(w).element as HTMLElement).focus(); await trigger(w).trigger("click"); await flushPromises(); expect(document.activeElement).toBe(trigger(w).element); }); it("honors per-item cancellation before changing or closing", async () => { const w = fixture( ``, ); await trigger(w).trigger("click"); await flushPromises(); await clickOption(0); expect(w.getComponent(Select).emitted("change")).toBeUndefined(); expect(trigger(w).attributes("aria-expanded")).toBe("true"); }); }); describe("Select async demo lifecycle", () => { it("loads a second page, retains existing options on failure, and retries", async () => { const original = globalThis.fetch; const cursors: string[] = []; let call = 0; globalThis.fetch = async (input) => { cursors.push(String(input)); call++; if (call === 2) return new Response("", { status: 503 }); return new Response( JSON.stringify( call === 1 ? { next: "https://pokeapi.co/api/v2/pokemon?offset=20", results: [{ name: "bulbasaur" }], } : { next: null, results: [{ name: "ivysaur" }] }, ), { status: 200 }, ); }; try { const { default: Demo } = await import("../apps/docs/demos/select-asynchronous-loading.vue"); const w = mount(Demo, { attachTo: document.body }); wrappers.push(w); await flushPromises(); await trigger(w).trigger("click"); await flushPromises(); const more = [ ...document.querySelectorAll( '[data-slot="select-popover"] button', ), ].find((button) => button.textContent?.includes("加载更多"))!; await new DOMWrapper(more).trigger("click"); await flushPromises(); expect(w.get("select").text()).toContain("bulbasaur"); const retry = [ ...document.querySelectorAll( '[data-slot="select-popover"] button', ), ].find((button) => button.textContent?.includes("重试"))!; expect(retry).toBeTruthy(); await new DOMWrapper(retry).trigger("click"); await flushPromises(); await vi.waitFor(() => expect(w.get("select").text()).toContain("ivysaur"), ); expect(cursors).toEqual([ "https://pokeapi.co/api/v2/pokemon", "https://pokeapi.co/api/v2/pokemon?offset=20", "https://pokeapi.co/api/v2/pokemon?offset=20", ]); } finally { globalThis.fetch = original; } }); it("aborts the pending request on unmount", async () => { const original = globalThis.fetch; let signal: AbortSignal | undefined; globalThis.fetch = async (_input, init) => { signal = init?.signal ?? undefined; return new Promise(() => {}); }; try { const { default: Demo } = await import("../apps/docs/demos/select-asynchronous-loading.vue"); const w = mount(Demo, { attachTo: document.body }); expect(signal?.aborted).toBe(false); w.unmount(); expect(signal?.aborted).toBe(true); } finally { globalThis.fetch = original; } }); }); describe("Select dynamic mode", () => { it("adapts uncontrolled single/multiple shapes and reset without synthetic edits", async () => { const mode = ref<"single" | "multiple">("single"); const w = fixture( `
`, () => ({ mode }), ); mode.value = "multiple"; await flushPromises(); expect(data()).toEqual([["choice", "last"]]); await trigger(w).trigger("click"); await flushPromises(); await clickOption(0); expect(w.getComponent(Select).emitted("change")).toEqual([[["last", 0]]]); mode.value = "single"; await flushPromises(); expect(data()).toEqual([["choice", "last"]]); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(data()).toEqual([["choice", "last"]]); expect(w.getComponent(Select).emitted("change")).toHaveLength(1); }); }); it("keeps locally disabled options out of the native submission even with explicit text metadata", () => { const w = fixture( `
`, ); expect(data()).toEqual([]); expect(w.get('[data-slot="select-value"]').text()).toBe("Alpha"); }); it("reveals only the currently focused owned option after popup positioning starts", async () => { const w = fixture(``); await trigger(w).trigger("click"); await flushPromises(); const active = option(3); const reveal = vi.fn(); active.scrollIntoView = reveal; const popup = document.querySelector( '[data-slot="select-popover"]', )!; popup.dispatchEvent(new Event("animationstart", { bubbles: true })); expect(reveal).toHaveBeenCalledOnce(); active.dispatchEvent(new Event("animationstart", { bubbles: true })); expect(reveal).toHaveBeenCalledOnce(); (trigger(w).element as HTMLElement).focus(); popup.dispatchEvent(new Event("animationstart", { bubbles: true })); expect(reveal).toHaveBeenCalledOnce(); });