Files
heroui-vue/tests/date-range-picker-demos.test.ts
T

304 lines
11 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { getLocalTimeZone, today } from "@internationalized/date";
const demos = import.meta.glob("../apps/docs/demos/date-range-picker-*.vue", {
eager: true,
import: "default",
});
const expected = [
"basic",
"disabled",
"controlled",
"with-validation",
"format-options",
"form-example",
"with-custom-indicator",
"render-function",
"international-calendar",
"custom-styles",
];
const wrappers: ReturnType<typeof mount>[] = [];
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
unobserve() {}
disconnect() {}
},
);
});
afterEach(async () => {
wrappers.splice(0).forEach((w) => w.unmount());
await flushPromises();
vi.useRealTimers();
vi.unstubAllGlobals();
document.body.innerHTML = "";
});
function mountDemo(name: string) {
const demo = demos[`../apps/docs/demos/date-range-picker-${name}.vue`];
const w = mount(demo as never, { attachTo: document.body });
wrappers.push(w);
return w;
}
async function open(w: ReturnType<typeof mount>) {
await w.get('[data-slot="date-range-picker-trigger"]').trigger("click");
await flushPromises();
}
function cell(date: string) {
return document.querySelector<HTMLElement>(
`[data-slot="range-calendar-cell"][data-date="${date}"]:not([data-outside-month])`,
);
}
async function pick(date: string) {
const target = cell(date);
expect(target).not.toBeNull();
target!.click();
await flushPromises();
}
function input(
w: ReturnType<typeof mount>,
slot: "start" | "end",
): HTMLInputElement {
return w.get(`[data-slot="date-range-picker-${slot}-value"]`)
.element as HTMLInputElement;
}
describe("DateRangePicker documentation", () => {
it("includes every pinned preview and uses the displayed SFC as its implementation", () => {
const md = readFileSync(
"apps/docs/components/date-range-picker.md",
"utf8",
);
expect(
[
...md.matchAll(/<ComponentPreview name="date-range-picker-([^"]+)"/g),
].map((match) => match[1]),
).toEqual(expected);
expect(md).not.toContain("[!toc]");
expect(Object.keys(demos)).toHaveLength(10);
});
it("mounts all ten examples without warnings or missing range controls", async () => {
const warnings: string[] = [];
for (const demo of Object.values(demos)) {
const w = mount(demo as never, {
global: {
config: { warnHandler: (message) => warnings.push(message) },
},
});
wrappers.push(w);
await flushPromises();
expect(w.find('[data-slot="date-range-picker"]').exists()).toBe(true);
expect(w.findAll('[data-slot="date-input-group-input"]')).toHaveLength(2);
expect(w.find('[data-slot="date-range-picker-trigger"]').exists()).toBe(
true,
);
expect(
w.findAll('[data-slot="date-input-group-segment"]').length,
).toBeGreaterThanOrEqual(6);
expect(w.findAll('input[data-part="start"]')).toHaveLength(1);
expect(w.findAll('input[data-part="end"]')).toHaveLength(1);
}
expect(warnings).toEqual([]);
});
it("the controlled example updates and clears the real range", async () => {
const w = mountDemo("controlled");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "清空")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(w.get('[data-slot="description"]').text()).toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "设为一周")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
});
it("the disabled example keeps values visible and non-editable", async () => {
const w = mountDemo("disabled");
await flushPromises();
expect(input(w, "start").disabled).toBe(true);
expect(input(w, "end").disabled).toBe(true);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(
w.get('[data-slot="date-range-picker-trigger"]').attributes("disabled"),
).toBeDefined();
expect(w.get('[data-slot="description"]').text()).toContain("已禁用");
});
it("format options keeps one range value while both TimeFields edit independently", async () => {
const w = mountDemo("format-options");
await flushPromises();
expect(input(w, "start").value).toContain("T08:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
await open(w);
const timeFields = document.querySelectorAll('[data-slot="time-field"]');
expect(timeFields).toHaveLength(2);
expect(document.querySelectorAll('[name="startTime"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endTime"]')).toHaveLength(1);
const hour =
timeFields[0]!.querySelector<HTMLElement>('[data-type="hour"]')!;
hour.focus();
hour.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowUp",
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
expect(input(w, "start").value).toContain("T09:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
expect(document.body.textContent).toContain("已选:");
expect(document.body.textContent).toContain("2026");
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endDate"]')).toHaveLength(1);
});
it("format options switches to day granularity without losing the picker", async () => {
const w = mountDemo("format-options");
await flushPromises();
const trigger = w.get('[data-slot="select-trigger"]');
await trigger.trigger("click");
await flushPromises();
const option = [
...document.querySelectorAll<HTMLElement>("[role=option]"),
].find((node) => node.textContent?.trim() === "日")!;
expect(option).toBeTruthy();
option.click();
await flushPromises();
expect(document.querySelectorAll('[data-slot="time-field"]')).toHaveLength(
0,
);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(input(w, "end").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
});
it("the form example submits a complete range and clears after success", async () => {
vi.useFakeTimers();
const w = mountDemo("form-example");
await flushPromises();
const submit = () =>
w.findAll("button").find((button) => button.text().includes("提交"))!;
expect(submit().attributes("disabled")).toBeDefined();
expect(w.findAll('[name="tripStartDate"]')).toHaveLength(1);
expect(w.findAll('[name="tripEndDate"]')).toHaveLength(1);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(submit().attributes("disabled")).toBeUndefined();
await w.get("form").trigger("submit");
await flushPromises();
expect(submit().text()).toContain("提交中");
vi.advanceTimersByTime(1300);
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(submit().text()).toBe("提交");
});
it("the custom indicator uses the Tabler icon instead of the default SVG", async () => {
const w = mountDemo("with-custom-indicator");
await flushPromises();
const icon = w.get('[data-slot="date-range-picker-trigger-indicator"] svg');
expect(icon.attributes("viewBox")).toBe("0 0 24 24");
expect(
w
.find(
'[data-slot="date-range-picker-trigger-indicator"] svg[viewBox="0 0 13 14"]',
)
.exists(),
).toBe(false);
});
it("the render-function example keeps consumer elements and attributes", async () => {
const w = mountDemo("render-function");
await flushPromises();
expect(w.get('[data-slot="date-range-picker"]').element.tagName).toBe(
"SECTION",
);
expect(
w.get('[data-slot="date-range-picker"]').attributes("data-custom"),
).toBe("date-range-picker");
expect(
w.get('[data-slot="date-input-group"]').attributes("data-custom"),
).toBe("date-field-group");
expect(
w
.get('[data-slot="date-range-picker-trigger"]')
.attributes("data-custom"),
).toBe("date-range-picker-trigger");
});
it("the international calendar displays its locale calendar and keeps values", async () => {
const w = mountDemo("international-calendar");
await flushPromises();
expect(input(w, "start").value).not.toBe("");
await open(w);
const header = document.querySelector(
'[data-slot="range-calendar-header-cell"]',
)?.textContent;
expect(header).toBeTruthy();
expect(header).not.toMatch(/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)$/);
const selected = document.querySelector(
'[data-slot="range-calendar-cell"][data-selection-start="true"]',
);
expect(selected).not.toBeNull();
});
it("the custom styles example applies consumer classes without component patches", async () => {
const w = mountDemo("custom-styles");
await flushPromises();
const group = w.get('[data-slot="date-input-group"]');
expect(group.classes()).toContain("rounded-xl");
expect(group.classes()).toContain("border");
expect(group.classes()).toContain("hv-date-input-group--secondary");
expect(
w.get('[data-slot="date-range-picker-range-separator"]').classes(),
).toContain("text-muted");
expect(
w.get('[data-slot="date-range-picker-trigger"]').classes(),
).toContain("text-muted");
await open(w);
expect(
document.querySelector('[data-slot="date-range-picker-popover"]')
?.className,
).toContain("border");
expect(
document.querySelector('[data-slot="range-calendar"]')?.className,
).toContain("bg-surface");
});
it("the validation example exposes required and invalid state through the form", async () => {
const w = mountDemo("with-validation");
await flushPromises();
const validation = w.get(".hv-choice-validation")
.element as HTMLInputElement;
expect(validation.checkValidity()).toBe(false);
await flushPromises();
expect(w.get('[data-slot="field-error"]').text()).toContain(
"请选择从今天起的有效日期范围",
);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(validation.checkValidity()).toBe(true);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
});
});