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

后端 未结 16 2030
面向向阳花
面向向阳花 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:30

    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.

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

    I solved in a very simple way:

    1. Set the value from props:
      const wrapper: ShallowWrapper = shallow(<ProfileViewClass name: 'Sample Name' />);
    
    1. Html code:
      <input type='text' defaultValue={props.name} className='edituser-name' />
    
    1. Access the attribute from wrapper.find(element).props().attribute-name:
      it('should render user name', () => {
        expect(wrapper.find('.edituser-name').props().defaultValue).toContain(props.name);
      });
    

    Cheers

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

    I'm using react with TypeScript and the following worked for me

    wrapper.find('input').getDOMNode<HTMLInputElement>().value = 'Hello';
    wrapper.find('input').simulate('change');
    

    Setting the value directly

    wrapper.find('input').instance().value = 'Hello'` 
    

    was causing me a compile warning.

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

    In case anyone is struggling, I found the following working for me

    const wrapper = mount(<NewTask {...props} />); // component under test
    const textField = wrapper.find(TextField);
    
    textField.props().onChange({ target: { value: 'New Task 2' } })
    textField.simulate('change');
    // wrapper.update() didn't work for me, need to find element again
    
    console.log(wrapper.find(TextField).props()); // New Task 2
    

    It seems that you need to define what happens in the change event first and then simulate it (instead of simulating the change event with data)

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