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

后端 未结 16 2031
面向向阳花
面向向阳花 2020-12-07 22:06

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

  it(\'cancels changes w         


        
相关标签:
16条回答
  • 2020-12-07 22:20

    I am using create-react-app which comes with jest by default and enzyme 2.7.0.

    This worked for me:

    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
    input.node.value = 'Change';
    input.simulate('change', input);
    done();
    
    0 讨论(0)
  • So lots of different opinions here. The only thing that worked for me was none of the above, it was using input.props().value. I hope that helps.

    0 讨论(0)
  • 2020-12-07 22:24

    This worked for me:

    let wrapped = mount(<Component />);
    expect(wrapped.find("input").get(0).props.value).toEqual("something");
    
    0 讨论(0)
  • 2020-12-07 22:24

    I use Wrapper's setValue[https://vue-test-utils.vuejs.org/api/wrapper/#setvalue-value] method to set value.

    inputA = wrapper.findAll('input').at(0)
    inputA.setValue('123456')
    
    0 讨论(0)
  • 2020-12-07 22:26

    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();
      });
    
    0 讨论(0)
  • 2020-12-07 22:27

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

    0 讨论(0)
提交回复
热议问题