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

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


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.


With Enzyme 3, if you need to change an input value but don't need to fire the onChange function you can just do this (node property has been removed):

wrapper.find('input').instance().value = "foo";

You can use wrapper.find('input').simulate("change", { target: { value: "foo" }}) to invoke onChange if you have a prop for that (ie, for controlled components).


Got it. (updated/improved version)

  it('cancels changes when user presses esc', done => {    const wrapper = mount(<EditableText defaultValue="Hello" />);    const input = wrapper.find('input');    input.simulate('focus');    input.simulate('change', { target: { value: 'Changed' } });    input.simulate('keyDown', {      which: 27,      target: {        blur() {          // Needed since <EditableText /> calls target.blur()          input.simulate('blur');        },      },    });    expect(input.get(0).value).to.equal('Hello');    done();  });