Files
heroui-vue/tests/autocomplete-demos.test.ts
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

234 lines
7.9 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { nextTick, type Component } from "vue";
import { readFileSync } from "node:fs";
const settle = () => new Promise((resolve) => setTimeout(resolve, 6));
const mounted: { unmount: () => void }[] = [];
const previews = [
"default",
"variants",
"full-width",
"with-description",
"required",
"disabled",
"with-disabled-options",
"allows-empty-collection",
"with-sections",
"multiple-select",
"controlled",
"controlled-multiple",
"controlled-open-state",
"asynchronous-filtering",
"custom-indicator",
"custom-value",
"on-surface",
"virtualization",
"user-selection",
"user-selection-multiple",
"location-search",
"tag-group-selection",
"email-recipients",
"custom-styles",
];
afterEach(async () => {
while (mounted.length) mounted.pop()?.unmount();
await nextTick();
await settle();
vi.restoreAllMocks();
document.body.innerHTML = "";
});
describe("Autocomplete docs and demos", () => {
it("keeps the pinned preview order and one demo per preview", () => {
const document = readFileSync(
"apps/docs/components/autocomplete.md",
"utf8",
);
const names = [
...document.matchAll(/<ComponentPreview name="autocomplete-([^"]+)"/g),
].map((match) => match[1]);
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/autocomplete-${name}.vue`,
"utf8",
);
expect(source, name).toContain("<template>");
expect(source, name).not.toContain("className");
expect(source, name).not.toContain("@gravity-ui/icons");
expect(source, name).not.toContain("<path");
}
});
it("uses the baseline search field shell and empty state in every demo", () => {
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/autocomplete-${name}.vue`,
"utf8",
);
// Upstream renders SearchField autoFocus name="search" variant="secondary"
// with a clear button; the popover filter must keep that whole shell.
const fields = [...source.matchAll(/<SearchField\b[^>]*>/g)];
expect(fields.length, name).toBeGreaterThan(0);
for (const [tag] of fields) {
expect(tag, name).toMatch(/\bvariant="secondary"/);
expect(tag, name).toMatch(/\bname="search"/);
expect(tag, name).toMatch(/\bauto-focus/);
}
expect(source, name).toContain("SearchFieldClearButton");
// The ported .hv-empty-state padding must not be overridden per demo.
expect(source, name).not.toMatch(/<EmptyState\s+class=/);
// Baseline feedback: only the required demo submits through the plain
// success alert, exactly like the pinned cn source.
if (name === "required") {
expect(source, name).toContain('alert("表单提交成功!")');
} else {
expect(source, name).not.toContain("alert(");
}
}
});
it("documents Vue props instead of React ones", () => {
const document = readFileSync(
"apps/docs/components/autocomplete.md",
"utf8",
);
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
expect(document).toContain("`class`");
expect(document).toContain("Vue class 绑定");
for (const part of [
"AutocompleteTrigger",
"AutocompleteValue",
"AutocompleteIndicator",
"AutocompleteClearButton",
"AutocompletePopover",
"AutocompleteFilter",
])
expect(document, part).toContain(`### ${part}`);
expect(document).not.toContain("[!toc]");
// React object-style part names must not appear as API table entries.
expect(document).not.toMatch(/\|\s*`Autocomplete\.[A-Z]\w*`\s*\|/);
});
it("mounts every demo with a named trigger", async () => {
const modules = import.meta.glob("../apps/docs/demos/autocomplete-*.vue");
expect(Object.keys(modules)).toHaveLength(previews.length);
for (const [path, load] of Object.entries(modules)) {
const demo = (await load()) as { default: Component };
const wrapper = mount(demo.default, { attachTo: document.body });
mounted.push(wrapper);
await nextTick();
const triggers = (wrapper.element as HTMLElement).querySelectorAll(
'[data-slot="autocomplete-trigger"]',
);
expect(triggers.length, path).toBeGreaterThan(0);
for (const element of triggers) {
expect(element.getAttribute("role"), path).toBe("button");
expect(element.getAttribute("aria-expanded"), path).toBe("false");
}
wrapper.unmount();
mounted.pop();
await settle();
document.body.innerHTML = "";
}
});
it("opens and filters inside representative demos", async () => {
for (const name of [
"default",
"multiple-select",
"with-sections",
"custom-styles",
"virtualization",
]) {
const demo = (await import(
`../apps/docs/demos/autocomplete-${name}.vue`
)) as { default: Component };
const wrapper = mount(demo.default, { attachTo: document.body });
mounted.push(wrapper);
await nextTick();
await settle();
const trigger = (
wrapper.element as HTMLElement
).querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
const search = document.querySelector<HTMLInputElement>(
'[data-slot="search-field-input"]',
);
expect(search, name).not.toBeNull();
expect(trigger.getAttribute("aria-expanded"), name).toBe("true");
const id = search!.getAttribute("aria-activedescendant");
expect(id, name).toBeTruthy();
expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
"option",
);
wrapper.unmount();
mounted.pop();
await settle();
document.body.innerHTML = "";
}
});
it("blocks empty required submits and keeps the baseline success alert", async () => {
const formDemo =
(await import("../apps/docs/demos/autocomplete-required.vue")) as {
default: Component;
};
const alert = vi.spyOn(window, "alert").mockImplementation(() => {});
const wrapper = mount(formDemo.default, { attachTo: document.body });
mounted.push(wrapper);
await nextTick();
await settle();
const root = wrapper.element as HTMLElement;
const pickerForm = (
root.matches("form") ? root : root.querySelector("form")
)!;
// Empty required pickers submit no entry; the Form guard blocks the submit.
expect(new FormData(pickerForm as HTMLFormElement).has("state")).toBe(
false,
);
expect(new FormData(pickerForm as HTMLFormElement).has("country")).toBe(
false,
);
// `Form` renders novalidate and guards submit itself: an empty required
// field must keep the demo's baseline alert silent.
const form = pickerForm;
const submit = (
wrapper.element as HTMLElement
).querySelector<HTMLButtonElement>('button[type="submit"]')!;
submit.click();
await nextTick();
await settle();
expect(form.getAttribute("novalidate")).not.toBeNull();
expect(alert).not.toHaveBeenCalled();
// Choose a value in both required pickers: the valid submit then fires
// the plain baseline success alert (cn/autocomplete/required.tsx).
for (const trigger of root.querySelectorAll<HTMLElement>(
'[data-slot="autocomplete-trigger"]',
)) {
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
const option = document.querySelector<HTMLElement>('[role="option"]')!;
option.click();
await nextTick();
await settle();
}
submit.click();
await nextTick();
await settle();
expect(alert).toHaveBeenCalledTimes(1);
expect(alert).toHaveBeenCalledWith("表单提交成功!");
wrapper.unmount();
mounted.pop();
alert.mockRestore();
});
});