How do you set the text of a text input and then test it's value with React / Enzyme?
const input = wrapper.find('#my-input'); input.simulate('change', { target: { value: 'abc' } } ); const val = input.node.value; //val is ''
All the solutions here appear not to work..
A few days ago, React released version 18, which is not compatible with Enzyme. Furthermore, it probably is not achievable to use Enzyme with React 18. If you're still using Enzyme, it is time to look into alternatives. The most popular option besides Enzyme seems to be React Testing Library.
To get the value of an input on button click in React: Declare a state variable that tracks the value of the input field. Add an onClick prop to a button element. When the button is clicked, update the state variable.
To really understand what's happening in your code it would be useful to see your component code (specifically your onChange
handler.
However, in regards to the following code:
input.simulate('change', {target: {value: 'abc'}});
This won't actually change the value of your <input />
element, instead it just causes your onChange
function to be run and be provided an event object that looks like {target: {value: 'abc'}}
.
The idea is that your onChange
function would update your state or store, so triggering this function should result in your DOM being updated. If you don't actually have an onChange
handler defined using input.simulate('change')
won't do anything.
So, if your goal is to actually set the value of an input and not trigger an onChange
handler then you can use JS to manually update the DOM using something like wrapper.find('#my-input').node.value = 'abc';
however this is circumventing React's render cycle and you'll likely see this value cleared/removed if you do anything to trigger a re-render.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With