enzyme: react-select simulate 'change' not working
How i can simulate ‘change’ event on react-select comonent?
wrapper.find('Select').simulate('change', { target: { value: 'text' }});
don’t trigger change event
wrapper.props().onChange(event) working well
any ideas?
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 10
- Comments: 16 (1 by maintainers)
@idoo so with
shallowI was able to get a passing test usingreact-select. You can see it here. enzyme-test-repo/tree/issue-#400. It seems that yourfindquery is not accurately querying the node that the change event should be simulated on. If you just useshallowand query for the<Select/>component you can easily test that theonChangeprop is being called.ReactSelectTestComponent.js
test.js
As for
mountit seems likely thatreact-selectisn’t actually registering a change event on the input your querying, I’d have to look at the source more but it doesn’t seem like they actually register anonChangehandler with their DOM nodes.If you look at the test files for
react-selectyou can see they are using a specific node to test change events:Where
searchInputNodeseems to be defined as:So you may want to follow that as an example of testing change events with
mount, thoughshallowdoes test theonChangeprop just fine.EDIT: rework for the
Select.AsyncHi all, I put it to work with the following code (I hope I don’t forget any portion of the code in the copy paste :-p ) :
The key was to add an
keyDownsimulation to validate thechangeevent@jamcreencia simulate doesn’t actually simulate anything, which is why i recommend avoiding it. It’s just sugar for invoking a prop function. If you want to invoke onChange, use
.prop(‘onChange’)().I have had similar issues simulating changes with react-select, possibly due to using MaterialUI as well.
The solutions explained so far did not work for me unfortunately, but I finally came across a solution which may be useful to those using MaterialUI, react-select and enzyme:
@Aweary
Had a similar issue trying to use Select.Async …Thanks to Aweary’s post I could achieve that in Enzyme
I created this utility function to Enzyme test react-select using Typescript. It returns a string reference to the component you can use to make assertions.
Usage:
Assert, where component is added to the test using
mount():@ljharb simulate has a problem in fact. Sometimes it working but for one test simulate not trigger event change. Atfer many tests, with my team we are arrived to invoke onChange by using
.invoke('onChange')()too.@idoo can you share your test case? If
wrapper.props().onChange(event)works then it should work withshallowsince allsimulatedoes with a shallow wrapper is map the event name the event handler in props (so'change'maps toprops.onChange)This is also potentially an issue with
react-select. It might not actually be registering change events the way you expect it to.