PettyUI/packages/core/tests/switch.test.ts
2026-03-31 23:03:52 +07:00

50 lines
1.6 KiB
TypeScript

import { describe, it, expect, beforeEach } from "vitest";
import { PettySwitch } from "../src/components/switch/index";
import { h } from "./helpers";
describe("petty-switch", () => {
let el: PettySwitch;
beforeEach(() => {
document.body.textContent = "";
el = document.createElement("petty-switch") as PettySwitch;
const btn = h("button", { "data-part": "control", type: "button" }, "Toggle");
const label = h("span", { "data-part": "label" }, "Dark mode");
el.appendChild(btn);
el.appendChild(label);
document.body.appendChild(el);
});
it("registers the custom element", () => {
expect(customElements.get("petty-switch")).toBe(PettySwitch);
});
it("sets role switch on button", () => {
const btn = el.querySelector("button")!;
expect(btn.getAttribute("role")).toBe("switch");
});
it("defaults to off state with aria-checked false", () => {
expect(el.checked).toBe(false);
expect(el.dataset.state).toBe("off");
expect(el.querySelector("button")!.getAttribute("aria-checked")).toBe("false");
});
it("toggles on click and fires petty-change", () => {
let detail: { checked: boolean } | null = null;
el.addEventListener("petty-change", ((e: CustomEvent) => {
detail = e.detail;
}) as EventListener);
el.querySelector("button")!.click();
expect(el.checked).toBe(true);
expect(el.dataset.state).toBe("on");
expect(detail).toEqual({ checked: true });
});
it("does not toggle when disabled", () => {
el.setAttribute("disabled", "");
el.querySelector("button")!.click();
expect(el.checked).toBe(false);
});
});