Files
next-tjwater-frontend/src/shared/ui/field-select.test.tsx
T

85 lines
2.7 KiB
TypeScript

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { FieldSelect } from "@/shared/ui/field-select";
import "@/test/radix-select-test-setup";
const options = [
{ value: "normal", label: "正常" },
{ value: "long", label: "名称很长但仍应完整换行显示的测点" },
{ value: "disabled", label: "不可选", disabled: true }
];
describe("FieldSelect", () => {
it("clears a controlled selection back to its placeholder without a change event", () => {
const onValueChange = vi.fn();
const view = render(
<FieldSelect
label="运行"
value="normal"
onValueChange={onValueChange}
options={options}
placeholder="选择运行"
/>
);
expect(screen.getByRole("combobox")).toHaveTextContent("正常");
view.rerender(
<FieldSelect
label="运行"
value=""
onValueChange={onValueChange}
options={options}
placeholder="选择运行"
/>
);
expect(screen.getByRole("combobox")).toHaveTextContent("选择运行");
expect(onValueChange).not.toHaveBeenCalled();
});
it("preserves the visible label and does not change value while opening", async () => {
const onValueChange = vi.fn();
const user = userEvent.setup();
render(
<FieldSelect label="场景" value="normal" onValueChange={onValueChange} options={options} />
);
const trigger = screen.getByRole("combobox", { name: "场景" });
expect(trigger).toHaveTextContent("正常");
expect(onValueChange).not.toHaveBeenCalled();
trigger.focus();
await user.keyboard(" ");
expect(screen.getByRole("option", { name: options[1].label })).toBeVisible();
expect(onValueChange).not.toHaveBeenCalled();
await user.keyboard("{Escape}");
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
expect(trigger).toHaveFocus();
expect(onValueChange).not.toHaveBeenCalled();
});
it("supports keyboard selection and skips empty-valued options", async () => {
const onValueChange = vi.fn();
const user = userEvent.setup();
render(
<FieldSelect
label="测点"
value=""
placeholder="选择测点"
onValueChange={onValueChange}
options={[{ value: "", label: "无效空项" }, ...options]}
/>
);
const trigger = screen.getByRole("combobox", { name: "测点" });
expect(trigger).toHaveTextContent("选择测点");
expect(screen.queryByText("无效空项")).not.toBeInTheDocument();
trigger.focus();
await user.keyboard(" ");
await user.keyboard("{ArrowDown}{Enter}");
expect(onValueChange).toHaveBeenCalledWith("long");
});
});