Open History to see the last commit
1import { act, useState } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5import { Switch } from "./switch";
6
7let root: Root;
8let container: HTMLDivElement;
9
10beforeEach(() => {
11 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
12 container = document.createElement("div");
13 document.body.append(container);
14 root = createRoot(container);
15});
16
17afterEach(async () => {
18 await act(async () => root.unmount());
19 container.remove();
20 vi.unstubAllGlobals();
21});
22
23function ControlledSwitch({
24 initialChecked,
25 initialMixed = false,
26}: {
27 initialChecked: boolean;
28 initialMixed?: boolean;
29}) {
30 const [checked, setChecked] = useState(initialChecked);
31 const [mixed, setMixed] = useState(initialMixed);
32
33 return (
34 <Switch
35 aria-label="Enable Claude Code"
36 checked={checked}
37 mixed={mixed}
38 onCheckedChange={(nextChecked) => {
39 setMixed(false);
40 setChecked(nextChecked);
41 }}
42 />
43 );
44}
45
46function switchRoot() {
47 const element = container.querySelector<HTMLElement>('[role="switch"]');
48 if (!element) throw new Error("Switch was not rendered");
49 return element;
50}
51
52async function clickSwitch() {
53 await act(async () => switchRoot().click());
54}
55
56async function renderSwitch(initialChecked: boolean, initialMixed = false) {
57 await act(async () => {
58 root.render(<ControlledSwitch {...{ initialChecked, initialMixed }} />);
59 });
60}
61
62describe("Switch accessibility", () => {
63 it.each([
64 { initialChecked: false, initialMixed: false, before: false, after: true },
65 { initialChecked: true, initialMixed: false, before: true, after: false },
66 { initialChecked: false, initialMixed: true, before: "mixed", after: true },
67 ])("exposes $before before activation and $after after activation", async (state) => {
68 await renderSwitch(state.initialChecked, state.initialMixed);
69 expect(switchRoot().getAttribute("aria-checked")).toBe(String(state.before));
70
71 await clickSwitch();
72
73 expect(switchRoot().getAttribute("aria-checked")).toBe(String(state.after));
74 expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked).toBe(
75 state.after,
76 );
77 });
78});