2

I'm using create-react-app 5 (with React 17, Jest, and testing-library), along with MUI 5. I'd like to test clicking a simple Select menu, and making sure the menu options appear. I tried the following:

  it('shows the menu', async () => {
    render(<FormControl fullWidth>
      <InputLabel id="testselect-label">Age</InputLabel>
      <Select
        labelId="testselect-label"
        id="testselect"
        data-testid="testselect"
        label="Age"
        value={10}
      >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>);
    const selectButton = screen.getByTestId("testselect");
    userEvent.click(selectButton);
    expect(await screen.findByRole('presentation')).toBeInTheDocument();
  });

But the menu (which has role="presentation") doesn't appear, so the test fails. If I call screen.debug() after the test, it prints the Select button, but not the menu.

I've already seen this question/answer, where I found that MUI5's Select responds to mouseDown events rather than click events. But userEvent.click sends both, so that's not the issue. I also tried fireEvent.mouseDown with no luck.

I also tried a debugger, and as far as I can tell, the onMouseDown handler of the relevant MUI component (SelectInput) is never called.

Does anyone have an example of this that works?

JW.
  • 50,691
  • 36
  • 115
  • 143
  • You need to use `mouseDown` instead of `click`. – Ryan Cogswell Sep 24 '22 at 02:31
  • @RyanCogswell I mentioned that above -- `userEvent.click` calls `mouseDown`, so that part's okay. I was clicking the wrong element though -- it needs to be the `button`. – JW. Sep 24 '22 at 03:29

1 Answers1

5

Looks like you need to click the button element:

    const selectButton = within(screen.getByTestId('testselect')).getByRole('button');
    userEvent.click(selectButton);
JW.
  • 50,691
  • 36
  • 115
  • 143