Search code examples
javascriptreactjstestingenzyme

Test setting text value with React and Enzyme


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


Solution

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