react-select icon indicating copy to clipboard operation
react-select copied to clipboard

Simulate 'change' doesn't work for select

Open nbotalov opened this issue 10 years ago • 18 comments

Hi, i'm adding tests to my pagination component based on Select

PageSizeSelector.js

class PageSizeSelector extends PureComponent {
    ..
    render() {
        const {pageSize} = this.props;
        return <Select
            options={this.pageSizeOptions}
            value={pageSize}
            onChange={(option) => this.pageSizeChangeFunc(option.value)()}
            clearable={false}
        />
    }
}

PageSizeSelector.test.js

import {mount} from 'enzyme'
...
it('changing pageSize', () => {
        let size = 0;
        const onPageSizeChanged = (pageSize) => size = pageSize;

        const wrapper = mount(
            <PageSizeSelector
                pageSize={10}
                onPageSizeChanged={onPageSizeChanged}
            />
        );

        wrapper.find('Select').simulate('change', {target: {value: 50}});
        expect(size).to.eql(50);
    })

onPageSizeChanged isn't called. If replace simulate line with

   wrapper.find('Select').find('input').simulate('change', {target: {value: 50}});

get exception

- TypeError: str.replace is not a function
        at stripDiacritics (node_modules/react-select/lib/utils/stripDiacritics.js:7:13)
        at filterOptions (node_modules/react-select/lib/utils/defaultFilterOptions.js:13:50)
        at filterOptions (node_modules/react-select/lib/Select.js:992:11)
        at render (node_modules/react-select/lib/Select.js:1116:45)
        at node_modules/react/lib/ReactCompositeComponent.js:793:21
        at measureLifeCyclePerf (node_modules/react/lib/ReactCompositeComponent.js:74:12)

Using react-select@^1.0.0-rc.2 Looked at https://github.com/airbnb/enzyme/issues/400 as well Thanks

nbotalov avatar Nov 07 '16 10:11 nbotalov

+10000000000000000 🎱

Cramsden avatar Nov 15 '16 19:11 Cramsden

@nbotalov hey, went across the same problem... Only solution I found was to simulate a selection through key-down events:

wrapper.find('.Select-control').simulate('keyDown', { keyCode: 40 }); // you can use 'input' instead of '.Select-control'
wrapper.find('.Select-control').simulate('keyDown', { keyCode: 13 });
expect(size).to.eql('your first value in the list')

stephane-ruhlmann avatar Apr 19 '17 08:04 stephane-ruhlmann

See https://stackoverflow.com/questions/41991077/testing-react-select-component/46201546#46201546

keithkml avatar Sep 13 '17 15:09 keithkml

I had to add the classNamePrefix prop to the Select component otherwise I didn't get any "control" classes to latch onto.

qaiken avatar Oct 19 '18 03:10 qaiken

This stackoverflow link shows how to simulate keyDown event. But if I do so, its not calling the onChange function.

sumanmaity112 avatar Feb 28 '19 12:02 sumanmaity112

The following should:

  1. Find the Select component in your wrapper.
  2. Get its instance.
  3. Set the value to { label: "...", value: 50 }
wrapper.find('Select').instance().selectOption({ label: "...", value: 50 });

If you can you should use the original options from your options array for tests.

Rall3n avatar Mar 08 '19 09:03 Rall3n

@Rall3n Thanks! Your solution worked for me!

ZeroDarkThirty avatar Jun 17 '19 03:06 ZeroDarkThirty

I answered the question using testing-library, easily adaptable to enzyme. For me, the Select is embedded in a component, but this still works, as long as you can pick the right input value.

https://stackoverflow.com/a/57699061/141552

Basically pretend to be a screen reader.

Using testing-library and v2.0

Trying to avoid using anything very specific like classNamePrefix or hacking into the way the component operates by looking for the onChange prop or whatever.

const callback = jest.fn();
const { container, getByText} = render(<Select ... onChange={callback} />);

Now we basically pretend to be a screen reader and focus, and press the down arrow.

fireEvent.focus(container.querySelector('input'));
fireEvent.keyDown(container.querySelector('input'), { key: 'ArrowDown', code: 40 });

And now click on the value you want

fireEvent.click(getByText('Option Two'));

And assert.

expect(callback).toHaveBeenCalledWith({ value: 'two', label: 'Option Two'});

dlikhten avatar Aug 28 '19 19:08 dlikhten

@Rall3n your solution worked for me!

And case I want remove? wrapper.find('Select').instance().removeOption({ label: "...", value: 50 })?

otalandim avatar Sep 16 '19 14:09 otalandim

The following should:

1. Find the `Select` component in your wrapper.

2. Get its instance.

3. Set the value to `{ label: "...", value: 50 }`
wrapper.find('Select').instance().selectOption({ label: "...", value: 50 });

If you can you should use the original options from your options array for tests.

It seems functions like selectOptions and removeOptions are in wrapper.find('Select').instance().props, not in wrapper.find('Select').instance()

soonoo avatar Feb 14 '20 01:02 soonoo

The react-testing-library solution has been extracted into a helper package: https://github.com/romgain/react-select-event

artdent avatar Feb 14 '20 04:02 artdent

Hello -

In an effort to sustain the react-select project going forward, we're closing old issues.

We understand this might be inconvenient but in the best interest of supporting the broader community we have to direct our efforts towards the current major version.

If you aren't using the latest version of react-select please consider upgrading to see if it resolves any issues you're having.

However, if you feel this issue is still relevant and you'd like us to review it - please leave a comment and we'll do our best to get back to you!

bladey avatar May 28 '20 05:05 bladey

Using react-select version 3.1.1 still its not working. Any plan to resolve this issue sooner?

Shhzdmrz avatar Jan 04 '21 14:01 Shhzdmrz

This works for me but there is some catch.

const simulateSelectChange = (
    component: ReactWrapper<{}, {}, React.Component<{}, {}, any>>,
    selector: string,
    option: string,
    printLog: boolean = false
) => {
    component.find(`${selector} div.select__input input`).simulate('change', { target: { value: option } });
    if (printLog) {
        console.warn(component.find(`${selector} .select__menu`).debug());
    }

    component.find(`${selector} .select__menu div[children="${option}"]`).simulate('click');
}

//and call it like this

simulateSelectChange(component, '#select-component-id', 'selectOption'),

Issue in that:

  1. To select an option you need to pass full option value to select the option.
  2. you cannot simulate integer list unless you make it as string.
  3. Simulate for Async Select will not work with this.

Shhzdmrz avatar Feb 01 '21 18:02 Shhzdmrz

It seems functions like selectOptions and removeOptions are in wrapper.find('Select').instance().props, not in wrapper.find('Select').instance()

Not sure, it related to result of wrapper.find... you must find correct Select element.

yanghoxom avatar Feb 25 '21 02:02 yanghoxom

The following should:

  1. Find the Select component in your wrapper.
  2. Get its instance.
  3. Set the value to { label: "...", value: 50 }
wrapper.find('Select').instance().selectOption({ label: "...", value: 50 });

If you can you should use the original options from your options array for tests.

Not working

akhilgkrishnan avatar Mar 09 '22 03:03 akhilgkrishnan

This answer helped me, I was not mocking a button value ([email protected] ) for the MouseEvent.

https://stackoverflow.com/a/52977609/1402195

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

 const toggleDropdownButton = wrapper
      .find(".my-select__indicator")
      .at(0)
      
  toggleDropdownButton.simulate('mouseDown', {
    button: 0 
  });

InSuperposition avatar Sep 17 '22 00:09 InSuperposition

It's working for me on mocha and enzyme, reactSelect is imported from 'react-select'

wrapper.find(reactSelect).at(0).props().onChange({ value: 'Engadget' });

stu01509 avatar Dec 14 '23 01:12 stu01509