Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  157] [ 2]  / answers: 1 / hits: 34068  / 8 Years ago, thu, january 19, 2017, 12:00:00

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..


More From » reactjs

 Answers
13

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.


[#59296] Tuesday, January 17, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;