Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 726
GN. Avatar asked Jan 19 '17 01:01

GN.


People also ask

Can you use Enzyme and React testing library together?

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.

How do you use React to set the value of an input?

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.


1 Answers

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.

like image 148
levi Avatar answered Sep 22 '22 12:09

levi