2.5 KB105 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @jest-environment jsdom
8 */
9
10import '@testing-library/jest-dom';
11import {act, fireEvent, render, screen} from '@testing-library/react';
12import {Provider} from 'jotai';
13import {ContextMenus, useContextMenu} from '../ContextMenu';
14
15const onClick1 = jest.fn();
16const onClick2 = jest.fn();
17
18function TestComponent() {
19 const menu = useContextMenu(() => [
20 {label: 'Context item 1', onClick: onClick1},
21 {label: 'Context item 2', onClick: onClick2},
22 ]);
23 return (
24 <div data-testid="test-component" onContextMenu={menu}>
25 Hello click me
26 </div>
27 );
28}
29
30function TestApp() {
31 return (
32 <Provider>
33 <div>
34 <TestComponent />
35 <ContextMenus />
36 </div>
37 </Provider>
38 );
39}
40
41function rightClick(el: HTMLElement) {
42 fireEvent.contextMenu(el);
43}
44
45describe('Context Menu', () => {
46 it('shows context menu items on right click', () => {
47 render(<TestApp />);
48
49 act(() => {
50 const component = screen.getByTestId('test-component');
51 rightClick(component);
52 });
53
54 expect(screen.getByText('Context item 1')).toBeInTheDocument();
55 expect(screen.getByText('Context item 2')).toBeInTheDocument();
56 });
57
58 it('runs callbacks on clicking an item', () => {
59 render(<TestApp />);
60
61 act(() => {
62 const component = screen.getByTestId('test-component');
63 rightClick(component);
64 });
65
66 act(() => {
67 fireEvent.click(screen.getByText('Context item 1'));
68 });
69 expect(onClick1).toHaveBeenCalled();
70 expect(onClick2).not.toHaveBeenCalled();
71 });
72
73 it('dismisses on escape key', () => {
74 render(<TestApp />);
75
76 act(() => {
77 const component = screen.getByTestId('test-component');
78 rightClick(component);
79 });
80
81 act(() => {
82 fireEvent.keyUp(window, {key: 'Escape'});
83 });
84
85 expect(screen.queryByText('Context item 1')).not.toBeInTheDocument();
86 expect(screen.queryByText('Context item 2')).not.toBeInTheDocument();
87 });
88
89 it('dismisses on click outside', () => {
90 render(<TestApp />);
91
92 act(() => {
93 const component = screen.getByTestId('test-component');
94 rightClick(component);
95 });
96
97 act(() => {
98 fireEvent.click(screen.getByTestId('test-component'));
99 });
100
101 expect(screen.queryByText('Context item 1')).not.toBeInTheDocument();
102 expect(screen.queryByText('Context item 2')).not.toBeInTheDocument();
103 });
104});
105