Files
heroui-vue/tests/number-field.test.ts

367 lines
13 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, ref, nextTick } from "vue";
import {
NumberField,
NumberFieldGroup,
NumberFieldInput,
NumberFieldIncrementButton,
NumberFieldDecrementButton,
Label,
Description,
FieldError,
Fieldset,
Form,
} from "../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
function fixture(template: string, setup = () => ({})) {
const w = mount(
defineComponent({
components: {
NumberField,
NumberFieldGroup,
NumberFieldInput,
NumberFieldIncrementButton,
NumberFieldDecrementButton,
Label,
Description,
FieldError,
Fieldset,
Form,
},
template,
setup,
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
const parts =
"<Label>Quantity</Label><NumberFieldGroup><NumberFieldDecrementButton/><NumberFieldInput/><NumberFieldIncrementButton/></NumberFieldGroup><Description>Choose quantity</Description><FieldError/>";
describe("NumberField public contracts", () => {
it("repeats a held step and clears timers on cancellation and unmount", async () => {
vi.useFakeTimers();
try {
const w = fixture(
`<NumberField :default-value="0">${parts}</NumberField>`,
);
const button = w.get('[data-slot="number-field-increment-button"]');
await button.trigger("pointerdown", { button: 0, pointerId: 1 });
await vi.advanceTimersByTimeAsync(460);
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"2",
);
await button.trigger("pointercancel");
await vi.advanceTimersByTimeAsync(1000);
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"2",
);
expect(vi.getTimerCount()).toBe(0);
await button.trigger("pointerdown", { button: 0, pointerId: 2 });
w.unmount();
wrappers.splice(wrappers.indexOf(w), 1);
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
it("updates ARIA/class attributes and controlled ownership as props are added and removed", async () => {
const attributes = ref<Record<string, unknown>>({});
const w = fixture(
`<NumberField :default-value="2" v-bind="attributes">${parts}</NumberField>`,
() => ({ attributes }),
);
for (const [index, label] of ["First", "Second"].entries()) {
attributes.value = {
"aria-label": label,
class: "custom-root",
modelValue: 7,
};
await nextTick();
expect(w.get('[role="spinbutton"]').attributes("aria-label")).toBe(label);
expect(w.get('[data-slot="number-field"]').classes()).toContain(
"custom-root",
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"7",
);
attributes.value = {};
await nextTick();
expect(
w.get('[role="spinbutton"]').attributes("aria-label"),
).toBeUndefined();
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
String(3 + index),
);
}
});
it("compiles and mounts all 17 baseline examples without Vue warnings", async () => {
const warnings: unknown[][] = [];
const warn = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args);
});
try {
const names = [
"basic",
"variants",
"on-surface",
"with-description",
"required",
"disabled",
"full-width",
"validation",
"controlled",
"with-step",
"with-format-options",
"form-example",
"with-validation",
"custom-icons",
"with-chevrons",
"render-function",
"custom-styles",
];
for (const name of names) {
const module = await import(
`../apps/docs/demos/number-field-${name}.vue`
);
const wrapper = mount(module.default, { attachTo: document.body });
try {
await nextTick();
expect(wrapper.findAll('[role="spinbutton"]').length).toBeGreaterThan(
0,
);
} finally {
wrapper.unmount();
}
}
} finally {
warn.mockRestore();
}
expect(warnings).toEqual([]);
});
it("steps decimals once and honors bounds and canonical FormData", async () => {
const w = fixture(
`<form><NumberField :default-value="0.2" :step="0.1" :min-value="0" :max-value="0.3" name="quantity">${parts}</NumberField></form>`,
);
await w.get('[data-slot="number-field-increment-button"]').trigger("click");
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"0.3",
);
expect(
(
w.get('[data-slot="number-field-increment-button"]')
.element as HTMLButtonElement
).disabled,
).toBe(true);
expect(new FormData(w.get("form").element).getAll("quantity")).toEqual([
"0.3",
]);
});
it("keeps empty controlled state when a parent rejects a step", async () => {
const update = vi.fn();
const w = fixture(
`<NumberField :model-value="null" @update:model-value="update">${parts}</NumberField>`,
() => ({ update }),
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(update).toHaveBeenCalledWith(0);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("");
expect(
w.get('[role="spinbutton"]').attributes("aria-valuenow"),
).toBeUndefined();
});
it("restores controlled text after rejected typing and clearing", async () => {
const w = fixture(`<NumberField :model-value="4">${parts}</NumberField>`);
const input = w.get('input[role="spinbutton"]');
for (const text of ["9", ""]) {
await input.setValue(text);
await input.trigger("blur");
await flushPromises();
expect((input.element as HTMLInputElement).value).toBe("4");
}
});
it("keeps characters typed after keydown instead of restoring committed text", async () => {
const update = vi.fn();
const w = fixture(
`<NumberField :model-value="4" @update:model-value="update">${parts}</NumberField>`,
() => ({ update }),
);
const input = w.get('input[role="spinbutton"]');
for (const [key, text] of [
["9", "49"],
["0", "490"],
] as const) {
// Keep keydown and text insertion in one task: awaiting trigger() here
// would flush the old nextTick(restore) before typing and hide the bug.
input.element.dispatchEvent(
new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }),
);
(input.element as HTMLInputElement).value = text;
input.element.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
await nextTick();
expect((input.element as HTMLInputElement).value).toBe(text);
}
await input.trigger("blur");
await flushPromises();
expect(update).toHaveBeenCalledWith(490);
});
it("blocks readonly Home End wheel click and typing", async () => {
const update = vi.fn();
const w = fixture(
`<NumberField :default-value="2" :min-value="0" :max-value="5" is-read-only @change="update">${parts}</NumberField>`,
() => ({ update }),
);
const input = w.get('[role="spinbutton"]');
for (const key of [
"Home",
"End",
"ArrowUp",
"ArrowDown",
"PageUp",
"PageDown",
])
await input.trigger("keydown", { key });
await input.setValue("9");
await input.trigger("blur");
await flushPromises();
await w.get('[data-slot="number-field-increment-button"]').trigger("click");
expect(update).not.toHaveBeenCalled();
expect((input.element as HTMLInputElement).value).toBe("2");
});
it("respects cancelled keyboard and button activation events", async () => {
const w = fixture(
`<NumberField :default-value="2"><NumberFieldInput @keydown.prevent/><NumberFieldIncrementButton @click.prevent/></NumberField>`,
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
await w.get("button").trigger("click");
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe("2");
});
it("resets noncontrolled values and preserves cancelled reset", async () => {
const w = fixture(
`<form><NumberField :default-value="2" name="quantity">${parts}</NumberField></form>`,
);
const input = w.get('[role="spinbutton"]');
await input.trigger("keydown", { key: "ArrowUp" });
w.get("form").element.reset();
await flushPromises();
expect(input.attributes("aria-valuenow")).toBe("2");
expect((input.element as HTMLInputElement).value).toBe("2");
expect(new FormData(w.get("form").element).get("quantity")).toBe("2");
w.get("form").element.addEventListener("reset", (e) => e.preventDefault());
await input.trigger("keydown", { key: "ArrowUp" });
w.get("form").element.reset();
await flushPromises();
expect(input.attributes("aria-valuenow")).toBe("3");
});
it("controlled reset preserves both visible and submitted parent value", async () => {
const w = fixture(
`<form><NumberField :model-value="8" :default-value="2" name="quantity">${parts}</NumberField></form>`,
);
w.get("form").element.reset();
await flushPromises();
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("8");
expect(new FormData(w.get("form").element).get("quantity")).toBe("8");
});
it("uses locale display and a single invariant submission value", async () => {
const w = fixture(
`<form><NumberField :default-value="1234.5" locale="de-DE" name="amount">${parts}</NumberField></form>`,
);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("1.234,5");
expect(new FormData(w.get("form").element).getAll("amount")).toEqual([
"1234.5",
]);
});
it("inherits Fieldset disabled and omits values", async () => {
const w = fixture(
`<form><Fieldset disabled><NumberField :default-value="2" name="quantity">${parts}</NumberField></Fieldset></form>`,
);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).disabled,
).toBe(true);
expect(new FormData(w.get("form").element).has("quantity")).toBe(false);
});
it("associates Label and multiple descriptions and removes stale references", async () => {
const show = ref(true);
const w = fixture(
`<NumberField><Label>Amount</Label><NumberFieldGroup><NumberFieldInput id="amount" aria-describedby="external"/></NumberFieldGroup><Description v-if="show" id="help">Help</Description></NumberField>`,
() => ({ show }),
);
expect(w.get("label").attributes("for")).toBe("amount");
expect(w.get("input").attributes("aria-describedby")).toContain("help");
show.value = false;
await nextTick();
expect(w.get("input").attributes("aria-describedby")).toBe("external");
});
it("blocks native invalid submit and surfaces FieldError", async () => {
const submit = vi.fn();
const w = fixture(
`<Form @submit="submit"><NumberField is-required>${parts}</NumberField><button type="submit">Submit</button></Form>`,
() => ({ submit }),
);
await w.get("form").trigger("submit");
expect(submit).not.toHaveBeenCalled();
expect(w.get('[data-slot="field-error"]').text()).toContain("请填写");
expect(document.activeElement).toBe(w.get('[role="spinbutton"]').element);
});
it("aria validation exposes errors without blocking submission", async () => {
const submit = vi.fn();
const w = fixture(
`<Form @submit.prevent="submit"><NumberField validation-behavior="aria" is-required>${parts}</NumberField></Form>`,
() => ({ submit }),
);
await w.get("form").trigger("submit");
expect(submit).toHaveBeenCalledTimes(1);
expect(w.get('[role="spinbutton"]').attributes("aria-invalid")).toBe(
"true",
);
});
});
it.each(["3", "5"])(
"keeps the submitted number-field snapshot when pending input changes to %s",
async (changed) => {
const { default: Demo } =
await import("../apps/docs/demos/number-field-form-example.vue");
const w = mount(Demo, { attachTo: document.body });
const log = vi.spyOn(console, "log").mockImplementation(() => {});
vi.useFakeTimers();
try {
const input = w.get("input[role=spinbutton]");
await input.setValue("2");
await input.trigger("blur");
await w.get("form").trigger("submit");
expect(w.get('button[type="submit"]').text()).toContain("…");
await input.setValue(changed);
await input.trigger("blur");
await w.get("form").trigger("submit");
await vi.advanceTimersByTimeAsync(1500);
expect(log).toHaveBeenCalledTimes(1);
expect(log.mock.calls[0][0]).toBe("Order submitted:");
expect(
String((log.mock.calls[0][1] as { quantity: unknown }).quantity),
).toBe("2");
expect((input.element as HTMLInputElement).value).toBe("");
} finally {
w.unmount();
log.mockRestore();
vi.useRealTimers();
}
},
);