Testing MUI5 Select with testing-library

Viewed 17

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?

1 Answers

Looks like you need to click the button element:

    const selectButton = within(screen.getByTestId('testselect')).getByRole('button');
    userEvent.click(selectButton);
Related