diff --git a/src/components/Menu/Menu.stories.tsx b/src/components/Menu/Menu.stories.tsx index dfab83d0f..4a7764582 100644 --- a/src/components/Menu/Menu.stories.tsx +++ b/src/components/Menu/Menu.stories.tsx @@ -55,8 +55,7 @@ export const Default: StoryObj = { > MDN: Menu - {/* eslint-disable-next-line no-alert */} - alert('Item clicked')}> + console.log('Item clicked')}> Trigger Action diff --git a/src/components/Menu/Menu.test.tsx b/src/components/Menu/Menu.test.tsx index e4a1abf06..6d9aefcbb 100644 --- a/src/components/Menu/Menu.test.tsx +++ b/src/components/Menu/Menu.test.tsx @@ -13,6 +13,9 @@ const { Default } = composeStories(stories); const { Opened, ...staticStories } = stories; describe('', () => { + afterEach(() => { + jest.resetAllMocks(); + }); generateSnapshots(staticStories, { getElement: async () => { const user = userEvent.setup(); @@ -46,6 +49,27 @@ describe('', () => { expect(menuContainer.getAttribute('aria-activedescendant')).not.toBeNull(); }); + it('handles onclick events when there is an href present', async () => { + // create a spy on the `log` method, and avoid calling it by setting the mock implementation to nothing + const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); + const user = userEvent.setup(); + render(); + const triggerButton = await screen.findByRole('button'); + await act(async () => { + await user.click(triggerButton); + }); + + await act(async () => { + await user.keyboard('{arrowdown}{arrowdown}{arrowdown}'); + }); + + await act(async () => { + await user.keyboard('{enter}'); + }); + + expect(consoleSpy).toHaveBeenCalledTimes(1); + }); + it('should close menu on keyboard escape key', async () => { const user = userEvent.setup(); render(); diff --git a/src/components/Menu/Menu.tsx b/src/components/Menu/Menu.tsx index d541a3696..5ae65d85e 100644 --- a/src/components/Menu/Menu.tsx +++ b/src/components/Menu/Menu.tsx @@ -42,7 +42,7 @@ export type MenuItemProps = ExtractProps & { */ icon?: IconName; /** - * Configurable action for the menu item action. If both `href` and `onClick` are used, `onClick` takes precedent. + * Configurable action for the menu item upon click */ onClick?: MouseEventHandler; }; @@ -189,8 +189,6 @@ const MenuItem = ({ onClick, ...other }: MenuItemProps) => { - // If we have an event handler, avoid navigation by discarding the href - const destinationUrl = !onClick ? href : undefined; return ( {({ active, disabled }) => { @@ -209,7 +207,7 @@ const MenuItem = ({ ) : ( {listItemView}