How to test material ui autocomplete with react testing library

First of all, you need to make sure the options are not empty array, then do the following:

const autocomplete = getByTestId('autocomplete');
const input = within(autocomplete).getByRole('textbox')
autocomplete.focus()
// the value here can be any string you want, so you may also consider to 
// wrapper it as a function and pass in inputValue as parameter
fireEvent.change(input, { target: { value: 'a' } })
fireEvent.keyDown(autocomplete, { key: 'ArrowDown' })
fireEvent.keyDown(autocomplete, { key: 'Enter' })

Leave a Comment