React Select is not keeping dropdown open in test but it is in browser

44 Views Asked by At

I have this:

<AsyncReactSelect
    defaultOptions
    loadOptions={async () => [
      { value: "Pear", label: "Pear" },
      { value: "Banana", label: "Banana" },
      { value: "Raspberry", label: "Raspberry" },
    ]}
    closeMenuOnSelect={false}
    isMulti
  />

enter image description here

that works as I expect. i.e. Pear was selected and the dropdown remained opened

in my test I have

await act(async () => {
  // open the dropdown
  const selectDropdown = screen.getAllByRole("combobox")[0]
  await userEvent.click(selectDropdown)

  await screen.findByText("Pear")
  screen.debug() // first debug
  await userEvent.type(selectDropdown, "{enter}")

  screen.debug() // second debug
})

in the first debug, I clear see all the dropdown options in a list

but in the second one, I can never see them and I have no clue as to why. I have tried fireEvent.click too as I wasn't sure if something odd was happening in the click functions.

any idea how to solve this?

EDIT:

I added in this and notice it's being called, it only gets called in the browser when I click outside the menu

 onMenuClose={() => {
          console.log("called the close!!")
        }}
2

There are 2 best solutions below

1
Mike K On

It's maybe because of this part that this is happening.

Try this:

await act(async () => {
  // open the dropdown
  const selectDropdown = screen.getAllByRole("combobox")[0]
  await userEvent.click(selectDropdown)

  await screen.findByText("Pear")
  screen.debug() // first debug
  // await userEvent.type(selectDropdown, "{enter}")
  userEvent.keyboard("{enter}");

  screen.debug() // second debug
})

Further reading here

3
Zia ul Qamar On

try this updated code

import React from "react";
import Select from "react-select";

const options = [
{ value: "1", label: "Test 1" },{ value: "2", label: "Test 2" },{ value: "3", label: "Test 3" },];


class App extends React.Component {
  state = { selectedOption: null};

handleChange = (selectedOption) => {

this.setState({ selectedOption }, () => console.log(`Option 
selected:`, this.state.selectedOption));
  };

render() {
const { selectedOption } = this.state;
 return <Select value={selectedOption} onChange={this.handleChange} options={options} />;
 }
}

actually, I want to ask you need to make your data structure like this data options array

also, you can see the documentation here: https://www.npmjs.com/package/react-select