Files
writer-work-flow/apps/web/lib/a11y/useRestoreFocus.test.ts

66 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// @vitest-environment jsdom
import { renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { RefObject } from "react";
import { useRestoreFocus } from "./useRestoreFocus";
const appended: HTMLElement[] = [];
function mountEl<T extends HTMLElement>(el: T): T {
document.body.appendChild(el);
appended.push(el);
return el;
}
afterEach(() => {
for (const el of appended.splice(0)) el.remove();
});
describe("useRestoreFocusCR-H11", () => {
it("关闭时把焦点还给 triggerRef", () => {
const trigger = mountEl(document.createElement("button"));
const other = mountEl(document.createElement("input"));
const ref: RefObject<HTMLElement | null> = { current: trigger };
const { rerender } = renderHook(
({ open }) => useRestoreFocus(open, ref),
{ initialProps: { open: true } },
);
other.focus();
expect(document.activeElement).toBe(other);
rerender({ open: false });
expect(document.activeElement).toBe(trigger);
});
it("从未打开过关闭态不抢焦点wasOpen 门闩)", () => {
const trigger = mountEl(document.createElement("button"));
const other = mountEl(document.createElement("input"));
const ref: RefObject<HTMLElement | null> = { current: trigger };
renderHook(({ open }) => useRestoreFocus(open, ref), {
initialProps: { open: false },
});
other.focus();
expect(document.activeElement).toBe(other);
});
it("triggerRef 为 null / undefined 时关闭不抛错", () => {
const nullRef: RefObject<HTMLElement | null> = { current: null };
const nullCase = renderHook(
({ open }) => useRestoreFocus(open, nullRef),
{ initialProps: { open: true } },
);
expect(() => nullCase.rerender({ open: false })).not.toThrow();
const undefCase = renderHook(
({ open }) => useRestoreFocus(open, undefined),
{ initialProps: { open: true } },
);
expect(() => undefCase.rerender({ open: false })).not.toThrow();
});
});