Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate selecting from dropdown in Jest / enzyme testing?

I'm trying to write jest tests for my React component that has a dropdown like this:

<select id="dropdown" onChange={this.handlechange} ref={this.refDropdown}>
    {this.props.items.map(item => {
        return (
            <option key={item.id} value={item.id}>
                {item.name}
            </option>
        );
    })}
</select>

and the handler looks like this:

handlechange = () => {
    const sel = this.refDropdown.current;
    const value = sel.options[sel.selectedIndex].value;
    //...
}

I want to simulate a user selecting the 2nd entry (or anything other than the first) in the list but am having trouble. If I simulate a "change" event it does fire the call to handlechange() but selectedIndex is always set to zero.

I tried this code in the jest test but it doesn't cause selectedIndex to be accessible in the handler.

const component = mount(<MyComponent/>);
component.find("#dropdown").simulate("change", {
    target: { value: "item1", selectedIndex: 1 }
});

What happens is almost correct. If I look at the incoming event, I can see e.value is set to "item1" as I set, but it doesn't act like the selection was actually made.

I've also tried trying to send "click" simulations to the Option element directly but that does nothing.

What's the right way to simulate a selection from a dropdown?

like image 851
Always Learning Avatar asked Oct 22 '18 13:10

Always Learning


3 Answers

Try this approach:

      wrapper.find('option').at(0).instance().selected = false;
      wrapper.find('option').at(1).instance().selected = true;
like image 57
flipback Avatar answered Sep 16 '22 11:09

flipback


You can trigger a change event since you have your this.handlechange trigger onChange:

const component = mount(<MyComponent/>);
component.find('#dropdown').at(0).simulate('change', {
    target: { value: 'item1', name: 'item1' }
});

I would say you have to add .at(0) because Enzyme will find a list of values even if you only have one element with that ID.

like image 45
aqteifan Avatar answered Sep 20 '22 11:09

aqteifan


Try changing the html "onInput" to "onChange" because you are simulating the "change" event in jest.

like image 37
kamesh roshan Avatar answered Sep 16 '22 11:09

kamesh roshan