Files
heroui-vue/tests/regressions/toast-table/visual-contracts.test.ts
T

445 lines
13 KiB
TypeScript

import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, ref, nextTick, computed } from "vue";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
EmptyState,
Table,
TableBody,
TableCell,
TableColumn,
TableCollection,
TableContent,
TableHeader,
TableRow,
ToastActionButton,
ToastCloseButton,
ToastContent,
ToastDescription,
ToastIndicator,
ToastProvider,
ToastQueue,
ToastTitle,
createToastFunction,
} from "../../../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
const queues: ToastQueue[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
queues.splice(0).forEach((q) => q.destroy());
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
vi.useRealTimers();
document.body.innerHTML = "";
});
function mountDemo(setup: () => unknown, render?: () => unknown) {
const w = mount(
defineComponent(
render
? { setup: setup as never, render: render as never }
: { setup: setup as never },
),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
it("TableBody #empty renders EmptyState without a data row", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, { "aria-label": "空表格" }, () => [
h(TableHeader, {}, () => h(TableColumn, {}, () => "姓名")),
h(
TableBody,
{ colspan: 1 },
{
empty: () =>
h(EmptyState, {}, () =>
h("span", { class: "msg" }, "未找到结果"),
),
},
),
]),
),
);
const body = w.get("tbody");
expect(body.attributes("data-empty")).toBeDefined();
expect(w.findAll("tr[data-slot='table-row']").length).toBe(0);
expect(w.find(".msg").text()).toBe("未找到结果");
expect(w.find("td[data-slot='table-empty-cell']").attributes("colspan")).toBe(
"1",
);
// Presentation row must not look like a selectable data row.
expect(w.find("tr[data-slot='table-empty-row']").attributes("role")).toBe(
"presentation",
);
expect(
w.find("tr[data-slot='table-empty-row']").attributes("aria-selected"),
).toBeUndefined();
});
it("TableBody keeps data rows when present and ignores #empty", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () => [
h(
TableBody,
{},
{
default: () =>
h(TableRow, { rowKey: "1" }, () => h(TableCell, {}, () => "A")),
empty: () => h("span", { class: "msg" }, "未找到结果"),
},
),
]),
),
);
expect(w.find(".msg").exists()).toBe(false);
expect(w.findAll("tr[data-slot='table-row']").length).toBe(1);
expect(w.get("tbody").attributes("data-empty")).toBeUndefined();
});
it("select-all checkbox supports indeterminate and shows 全部 when complete", async () => {
const users = [
{ id: "1", name: "Kate" },
{ id: "2", name: "John" },
{ id: "3", name: "Sara" },
];
const selectedKeys = ref<string[]>([]);
const w = mountDemo(
() => {
const allChecked = computed(
() => users.length > 0 && selectedKeys.value.length === users.length,
);
const someChecked = computed(
() => selectedKeys.value.length > 0 && !allChecked.value,
);
return {
selectedKeys,
allChecked,
someChecked,
users,
};
},
function (this: {
selectedKeys: string[];
allChecked: boolean;
someChecked: boolean;
users: typeof users;
}) {
return h("div", [
h(Checkbox, {
ariaLabel: "全选",
isSelected: this.allChecked,
isIndeterminate: this.someChecked,
"onUpdate:checked": () => {
this.selectedKeys = this.allChecked
? []
: this.users.map((u) => u.id);
},
}),
h(
"p",
{ class: "summary" },
this.allChecked
? "全部"
: this.selectedKeys.length
? this.selectedKeys.join(", ")
: "无",
),
]);
},
);
expect(w.find(".summary").text()).toBe("无");
const input = w.get("input");
expect(input.element.indeterminate).toBe(false);
selectedKeys.value = ["1"];
await nextTick();
expect(w.find(".summary").text()).toBe("1");
expect(w.get("input").element.indeterminate).toBe(true);
selectedKeys.value = ["1", "2", "3"];
await nextTick();
expect(w.find(".summary").text()).toBe("全部");
expect(w.get("input").element.indeterminate).toBe(false);
expect(w.get("input").element.checked).toBe(true);
});
it("row checkbox click does not also toggle row selection", async () => {
const selectionChanges: unknown[] = [];
const w = mountDemo(
() => ({ selectionChanges }),
function (this: { selectionChanges: unknown[] }) {
return h(Table, {}, () =>
h(
TableContent,
{
selectionMode: "multiple",
onSelectionChange: (keys: unknown) =>
this.selectionChanges.push(keys),
},
() =>
h(TableBody, {}, () =>
h(
TableRow,
{ rowKey: "1" },
{
default: () => [
h(TableCell, {}, () =>
h(
Checkbox,
{},
{
default: () => [
h(
CheckboxContent,
{},
{
default: () => [
h(CheckboxControl, {}, () =>
h(CheckboxIndicator),
),
],
},
),
],
},
),
),
h(TableCell, {}, () => "Kate"),
],
},
),
),
),
);
},
);
const label = w.get("label[data-slot='checkbox-content']");
await label.trigger("click");
await nextTick();
// Clicking the choice control must not bubble into row selection.
expect(
(w.vm as unknown as { selectionChanges: unknown[] }).selectionChanges,
).toEqual([]);
});
it("toast root is alertdialog with title/description ids and content role=alert", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
const w = mountDemo(
() => ({ queue }),
() =>
h(
ToastProvider,
{ queue: queue as never, to: "body" },
{
default: ({
toast: item,
close,
}: {
toast: { title: string; description: string };
close: () => void;
}) =>
h(ToastContent, {}, () => [
h(ToastTitle, () => item.title),
h(ToastDescription, () => item.description),
h(ToastActionButton, { onClick: () => close() }, () => "忽略"),
h(ToastCloseButton, { onClick: () => close() }),
]),
},
),
);
toast("您已被邀请加入团队", {
description: "Bob 邀请您加入 HeroUI 团队",
timeout: 0,
});
await flushPromises();
await nextTick();
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
expect(root).toBeTruthy();
expect(root.getAttribute("role")).toBe("alertdialog");
expect(root.getAttribute("aria-modal")).toBe("false");
const title = root.querySelector('[data-slot="toast-title"]') as HTMLElement;
const desc = root.querySelector(
'[data-slot="toast-description"]',
) as HTMLElement;
expect(title.id).toBeTruthy();
expect(desc.id).toBeTruthy();
expect(root.getAttribute("aria-labelledby")).toBe(title.id);
expect(root.getAttribute("aria-describedby")).toBe(desc.id);
const content = root.querySelector(
'[data-slot="toast-content"]',
) as HTMLElement;
expect(content.getAttribute("role")).toBe("alert");
expect(content.getAttribute("aria-atomic")).toBe("true");
// After mount the alert payload is visible so it can be announced.
await nextTick();
expect(content.getAttribute("aria-hidden")).not.toBe("true");
// Close button keeps an accessible name.
const close = root.querySelector("[data-slot='toast-close']");
expect(close?.getAttribute("aria-label")).toBeTruthy();
void w;
});
it("toast indicator sets data-swapped only after the first paint", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
mountDemo(
() => ({ queue }),
() =>
h(
ToastProvider,
{ queue: queue as never, to: "body" },
{
default: ({
toast: item,
}: {
toast: { title: string; isLoading?: boolean; variant?: string };
}) =>
h(ToastContent, {}, () => [
h(ToastTitle, () => item.title),
h(
ToastIndicator,
{ variant: (item.variant ?? "default") as never },
item.isLoading
? () => h("span", { "data-slot": "spinner" })
: undefined,
),
]),
},
),
);
const loadingId = toast("正在上传文件…", { isLoading: true, timeout: 0 });
await flushPromises();
await nextTick();
const indicator = () =>
document.querySelector('[data-slot="toast-indicator"]') as HTMLElement;
expect(indicator().getAttribute("data-swapped")).toBeNull();
toast.update(loadingId, "文件已上传", {
isLoading: false,
variant: "success",
timeout: 0,
});
await flushPromises();
await nextTick();
expect(indicator().getAttribute("data-swapped")).toBe("true");
});
it("column defaultWidth 1fr does not write an invalid CSS width", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(TableHeader, {}, () =>
h(TableColumn, { id: "name", defaultWidth: "1fr" }, () => "姓名"),
),
),
),
);
const th = w.get("th");
expect((th.element as HTMLElement).style.width).toBe("");
expect(th.attributes("data-default-width")).toBe("1fr");
});
it("tree column cell gets data-tree-column and row level variable", () => {
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, { treeColumn: "name" }, () => [
h(TableHeader, {}, () =>
h(TableColumn, { id: "name" }, () => "姓名"),
),
h(TableBody, {}, () =>
h(TableRow, { rowKey: "1", level: 2, hasChildItems: true }, () =>
h(TableCell, {}, () => "文档"),
),
),
]),
),
);
const tr = w.get("tr[data-slot='table-row']");
expect(tr.attributes("data-level")).toBe("2");
expect(
(tr.element as HTMLElement).style.getPropertyValue("--table-row-level"),
).toBe("2");
const td = w.get("td[data-slot='table-cell']");
expect(td.attributes("data-tree-column")).toBeDefined();
});
it("TableCollection empty ↔ non-empty toggles the empty slot", async () => {
const items = ref<string[]>([]);
const w = mountDemo(
() => () =>
h(Table, {}, () =>
h(TableContent, {}, () =>
h(
TableBody,
{ colspan: 1 },
{
default: () =>
h(
TableCollection,
{ items: items.value },
{
default: ({ item }: { item: string }) =>
h(TableRow, { rowKey: item }, () =>
h(TableCell, {}, () => item),
),
},
),
empty: () => h("span", { "data-test": "empty" }, "Empty"),
},
),
),
),
);
expect(w.find('[data-test="empty"]').exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
items.value = ["A", "B"];
await nextTick();
expect(w.find('[data-test="empty"]').exists()).toBe(false);
expect(w.findAll('[data-slot="table-row"]').length).toBe(2);
items.value = [];
await nextTick();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
});
it("title-only toast omits aria-describedby when no description part exists", async () => {
const queue = new ToastQueue();
queues.push(queue);
const toast = createToastFunction(queue);
mountDemo(
() => ({ queue }),
() => h(ToastProvider, { queue: queue as never, to: "body" }),
);
toast("标题独占", { timeout: 0 });
await flushPromises();
await nextTick();
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
const refs = (root.getAttribute("aria-describedby") ?? "")
.split(/\s+/)
.filter(Boolean);
expect(refs.length).toBe(0);
const labelled = root.getAttribute("aria-labelledby");
expect(labelled && document.getElementById(labelled)).toBeTruthy();
});