@react-spectrum/test-utils offers common menu interaction testing utilities. Install it with your preferred package manager.
Initialize a User object at the top of your test file, and use it to create a Menu pattern tester in your test cases. The tester has methods that you can call within your test to query for specific subcomponents or simulate common interactions.
// Menu.test.tsimport {render} from'@testing-library/react';
import {User} from'@react-spectrum/test-utils';
lettestUtilUser = new User({
interactionType: 'mouse'
});
// ...it('Menu can open its submenu via keyboard', asyncfunction () {
// Render your test component/app and initialize the menu testerlet {getByTestId} = render(
<MenuTrigger>
<Button data-testid="test-menutrigger">Menu trigger</Button> ... </MenuTrigger>
);
letmenuTester = testUtilUser.createTester('Menu', {root: getByTestId('test-menutrigger'), interactionType: 'keyboard'});
awaitmenuTester.open();
expect(menuTester.menu).toBeInTheDocument();
letsubmenuTriggers = menuTester.submenuTriggers;
expect(submenuTriggers).toHaveLength(1);
letsubmenuTester = awaitmenuTester.openSubmenu({submenuTrigger: 'Share…'});
expect(submenuTester.menu).toBeInTheDocument();
awaitsubmenuTester.selectOption({option: submenuTester.options()[0]});
expect(submenuTester.menu).not.toBeInTheDocument();
expect(menuTester.menu).not.toBeInTheDocument();
});
API
Properties
Name
Type
Default
advanceTimer
UserOpts['advanceTimer']
Default: —
A function used by the test utils to advance timers during interactions. Required for certain aria patterns (e.g. table).
interactionType
UserOpts['interactionType']
Default: mouse
The interaction type (mouse, touch, keyboard) that the test util user will use when interacting with a component. This can be overridden
at the aria pattern util level if needed.
Selects the desired menu option. Defaults to using the interaction type set on the menu tester. If necessary, will open the menu dropdown beforehand.
The desired option can be targeted via the option's node, the option's text, or the option's index.
Opens the submenu. Defaults to using the interaction type set on the menu tester. The submenu trigger can be targeted via the trigger's node or the trigger's text.
Returns the menu's options if present. Can be filtered to a subsection of the menu if provided via element.
Testing FAQ
In cases like this, first double check your test setup and make sure that your test is rendering your menu in its expected state before the test util interaction call. If everything looks correct, you can always fall back to simulating interactions manually, and using the test util to query your menu's state post interaction.
Whenever the menu tester queries its elements or triggers a user flow, it does so against the current state of the menu. Therefore the menu tester can be used alongside whatever simulated user flow you add.