Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme - How to access and set <input> value?

I'm confused about how to access <input> value when using mount. Here's what I've got as my test:

  it('cancels changes when user presses esc', done => {     const wrapper = mount(<EditableText defaultValue="Hello" />);     const input = wrapper.find('input');      console.log(input.render().attr('value'));     input.simulate('focus');     done();   }); 

The console prints out undefined. But if I slightly modify the code, it works:

  it('cancels changes when user presses esc', done => {     const wrapper = render(<EditableText defaultValue="Hello" />);     const input = wrapper.find('input');      console.log(input.val());     input.simulate('focus');     done();   }); 

Except, of course, the input.simulate line fails since I'm using render now. I need both to work properly. How do I fix this?

EDIT:

I should mention, <EditableText /> is not a controlled component. But when I pass defaultValue into <input />, it seems to set the value. The second code block above does print out the value, and likewise if I inspect the input element in Chrome and type $0.value in the console, it shows the expected value.

like image 403
ffxsam Avatar asked May 13 '16 21:05

ffxsam


People also ask

How do you change the input value of an enzyme?

If you want to change the input's value, set the value prop on it; if you want to invoke an onChange , invoke it. If you're doing something unidiomatic for React, and binding events directly to reffed DOM elements, then you'll have to test them by directly interacting with the DOM elements as well.


1 Answers

I think what you want is:

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

Here's my source.

You shouldn't need to use render() anywhere to set the value. And just FYI, you are using two different render()'s. The one in your first code block is from Enzyme, and is a method on the wraper object mount and find give you. The second one, though it's not 100% clear, is probably the one from react-dom. If you're using Enzyme, just use shallow or mount as appropriate and there's no need for render from react-dom.

like image 161
Tyler Collier Avatar answered Sep 18 '22 12:09

Tyler Collier