Test parameter value for setting with reagent and enzyme

How do you set text input text and then check its value with React / Enzyme?

const input = wrapper.find('#my-input'); input.simulate('change', { target: { value: 'abc' } } ); const val = input.node.value; //val is '' 

All solutions here do not seem to work.

+7
javascript reactjs testing enzyme
source share
3 answers

To really understand what is happening in your code, it would be useful to see your component code (in particular, your onChange handler.

However, with regard to the following code:

 input.simulate('change', {target: {value: 'abc'}}); 

This will not actually change the value of your <input /> element, instead, it will simply run your onChange function and an event object will be provided that looks like {target: {value: 'abc'}} .

The idea is that your onChange function onChange updated your state or storage, so enabling this function will update your DOM. Unless you actually have an onChange handler defined with input.simulate('change') , it will do nothing.

So, if your goal is to actually set the input value and not start the onChange handler, then you can use JS to manually update the DOM with something like wrapper.find('#my-input').node.value = 'abc'; however, this bypasses the React rendering cycle, and you are likely to have this value cleared / deleted if you do anything to cause a re-rendering.

+8
source share

I use React 16 and Enzyme 3.10 here, and it worked for me completely (by trying too many different sentences):

 wrapper.find("input").instance().value = "abc"; 

Apparently in previous versions you could use node or getNode() instead of instance() , which were part of my previous attempts.

+5
source share

This works for both enzyme 3 and enzyme 2:

 wrapper.find('input').getDOMNode().value = 'new value'; wrapper.find('input').simulate('change'); 

.getDOMNode() can be used as .node in enzyme 2 and as .instance() in enzyme 3.

+3
source share

All Articles