1import React from 'react'; 2import { render, screen } from '@testing-library/react'; 3import { fireEvent } from '@testing-library/dom'; 4import { selectors } from '@grafana/e2e-selectors'; 5import { MenuItem, MenuItemProps } from './MenuItem'; 6 7describe('MenuItem', () => { 8 const getMenuItem = (props?: Partial<MenuItemProps>) => ( 9 <MenuItem ariaLabel={selectors.components.Menu.MenuItem('Test')} label="item1" icon="history" {...props} /> 10 ); 11 12 it('renders correct element type', () => { 13 const { rerender } = render(getMenuItem({ onClick: jest.fn() })); 14 15 expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('BUTTON'); 16 17 rerender(getMenuItem({ url: 'test' })); 18 19 expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('A'); 20 }); 21 22 it('calls onClick when item is clicked', () => { 23 const onClick = jest.fn(); 24 25 render(getMenuItem({ onClick })); 26 27 fireEvent.click(screen.getByLabelText(selectors.components.Menu.MenuItem('Test'))); 28 29 expect(onClick).toHaveBeenCalled(); 30 }); 31 32 it('renders and opens subMenu correctly', async () => { 33 const childItems = [ 34 <MenuItem key="subitem1" label="subitem1" icon="history" />, 35 <MenuItem key="subitem2" label="subitem2" icon="apps" />, 36 ]; 37 38 render(getMenuItem({ childItems })); 39 40 expect(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')).nodeName).toBe('DIV'); 41 expect(screen.getByLabelText(selectors.components.Menu.SubMenu.icon)).toBeInTheDocument(); 42 expect(screen.queryByLabelText(selectors.components.Menu.SubMenu.container)).not.toBeInTheDocument(); 43 44 fireEvent.mouseOver(screen.getByLabelText(selectors.components.Menu.MenuItem('Test'))); 45 46 const subMenuContainer = await screen.findByLabelText(selectors.components.Menu.SubMenu.container); 47 48 expect(subMenuContainer).toBeInTheDocument(); 49 expect(subMenuContainer.firstChild?.childNodes.length).toBe(2); 50 }); 51 52 it('opens subMenu on ArrowRight', async () => { 53 const childItems = [ 54 <MenuItem key="subitem1" label="subitem1" icon="history" />, 55 <MenuItem key="subitem2" label="subitem2" icon="apps" />, 56 ]; 57 58 render(getMenuItem({ childItems })); 59 60 expect(screen.queryByLabelText(selectors.components.Menu.SubMenu.container)).not.toBeInTheDocument(); 61 62 fireEvent.keyDown(screen.getByLabelText(selectors.components.Menu.MenuItem('Test')), { key: 'ArrowRight' }); 63 64 expect(await screen.findByLabelText(selectors.components.Menu.SubMenu.container)).toBeInTheDocument(); 65 }); 66}); 67