-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathdropdown-menu.spec.tsx
More file actions
118 lines (106 loc) · 2.59 KB
/
Copy pathdropdown-menu.spec.tsx
File metadata and controls
118 lines (106 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// @vitest-environment jsdom
import { MenuGroup } from '@wordpress/components';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { DropdownMenu } from './dropdown-menu';
describe('DropdownMenu', () => {
let container: HTMLDivElement;
let root: Root;
beforeAll(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
);
});
afterAll(() => {
vi.unstubAllGlobals();
});
beforeEach(() => {
container = document.createElement('div');
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it('adds Home and End navigation without replacing the menu key handler', async () => {
const onKeyDown = vi.fn();
await act(async () => {
root.render(
<DropdownMenu
icon={null}
label="Actions"
menuProps={{ onKeyDown }}
popoverProps={{ focusOnMount: false }}
>
{() => (
<MenuGroup>
<button type="button" role="menuitem">
First
</button>
<button type="button" role="menuitem">
Middle
</button>
<button type="button" role="menuitem">
Last
</button>
</MenuGroup>
)}
</DropdownMenu>
);
});
await act(async () => getButton('Actions').click());
const menu = document.querySelector<HTMLElement>(
'[role="menu"][aria-label="Actions"]'
);
const menuItems =
menu?.querySelectorAll<HTMLElement>('[role="menuitem"]');
if (!menuItems || menuItems.length !== 3) {
throw new Error(
'Expected the Actions menu to contain three items.'
);
}
act(() => {
menuItems[1].focus();
menuItems[1].dispatchEvent(
new KeyboardEvent('keydown', {
key: 'Home',
code: 'Home',
bubbles: true,
})
);
});
expect(document.activeElement).toBe(menuItems[0]);
act(() => {
menuItems[0].dispatchEvent(
new KeyboardEvent('keydown', {
key: 'End',
code: 'End',
bubbles: true,
})
);
});
expect(document.activeElement).toBe(menuItems[2]);
expect(onKeyDown).toHaveBeenCalledTimes(2);
});
function getButton(name: string): HTMLButtonElement {
const button = container.querySelector<HTMLButtonElement>(
`button[aria-label="${name}"]`
);
if (!button) {
throw new Error(`Button not found: ${name}`);
}
return button;
}
});