Files
Genarrative/apps/ai-game-creator-shell/tests/themedModal.test.tsx
T
k88936 5528fdf64a 补齐主题弹窗焦点管理
接入 focus-trap-react 统一管理弹窗焦点生命周期

覆盖初始焦点、Tab 循环及关闭后焦点归还

更新 AI 游戏创作弹窗无障碍契约
2026-08-19 13:04:05 +08:00

109 lines
3.2 KiB
TypeScript

// @vitest-environment jsdom
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ThemedModal } from '../src/components/modal/ThemedModal';
function ModalHarness({ noFocusableContent = false }) {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>
打开弹窗
</button>
<ThemedModal
open={open}
onClose={() => setOpen(false)}
ariaLabel="测试弹窗"
>
{noFocusableContent ? (
<p>没有可聚焦控件</p>
) : (
<>
<button type="button" onClick={() => setOpen(false)}>
取消
</button>
<button type="button">确认</button>
</>
)}
</ThemedModal>
</>
);
}
describe('ThemedModal', () => {
beforeEach(() => {
vi.spyOn(HTMLElement.prototype, 'getClientRects').mockImplementation(
() =>
[
{
width: 1,
height: 1,
top: 0,
right: 1,
bottom: 1,
left: 0,
x: 0,
y: 0,
toJSON: () => ({}),
},
] as unknown as DOMRectList,
);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('moves focus into the dialog, traps Tab, and restores the opener after close', async () => {
const user = userEvent.setup();
render(<ModalHarness />);
const opener = screen.getByRole('button', { name: '打开弹窗' });
await user.click(opener);
const cancel = await screen.findByRole('button', { name: '取消' });
const confirm = screen.getByRole('button', { name: '确认' });
await waitFor(() => expect(document.activeElement).toBe(cancel));
await user.tab();
expect(document.activeElement).toBe(confirm);
await user.tab();
expect(document.activeElement).toBe(cancel);
await user.tab({ shift: true });
expect(document.activeElement).toBe(confirm);
await user.keyboard('{Escape}');
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(document.activeElement).toBe(opener);
});
it('focuses the dialog itself when it has no focusable content', async () => {
const user = userEvent.setup();
render(<ModalHarness noFocusableContent />);
await user.click(screen.getByRole('button', { name: '打开弹窗' }));
const dialog = await screen.findByRole('dialog', { name: '测试弹窗' });
await waitFor(() => expect(document.activeElement).toBe(dialog));
});
it('restores focus after a backdrop close', async () => {
const user = userEvent.setup();
render(<ModalHarness />);
const opener = screen.getByRole('button', { name: '打开弹窗' });
await user.click(opener);
const dialog = await screen.findByRole('dialog', { name: '测试弹窗' });
fireEvent.click(dialog.parentElement!);
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(document.activeElement).toBe(opener);
});
});