Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let say I have a component to calculate and display a result from 2 inputs as below. Now I want to test onChange event for input state change.

class CalcForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputFirstNum: 1,
      inputLastNum: 30,
      answer: [10, 20, 30]
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value,
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
    answer: mySampleFunction(this.state.inputFirstNum, this.state.inputLastNum),
  });   
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit} className="container-fluid">
          <input type="number" 
                onChange={this.handleChange} 
                value={this.state.inputFirstNum} />
          <input type="number" 
                onChange={this.handleChange} 
                value={this.state.inputLastNum} />
          <input type="submit" value="Go"/>
        </div>
        <div id="result">
          {this.state.answer.join(', ')}
        </div>   
      </form>
    );
  }
}
export default CalcForm;

Here is my test:

it('should change the value on 1st-input', () => {
  const wrapper = shallow(<CalcForm />);
  wrapper.find('input[type="number"]').at(0).simulate('change', { 
    target: { value: 111 } 
  });
  expect(wrapper.find('input[type="number"]').at(0).prop('value')).toEqual(111);
});

The received is always the default value, as followings:

Expected: 111
Received: 1

Am I missing something?

question from:https://stackoverflow.com/questions/65936824/state-is-always-default-value-when-test-with-another-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
132 views
Welcome To Ask or Share your Answers For Others

1 Answer

Ok I figured out what's the issue with your code.

First you have assigned the name attribute to your inputs in the component.

<input
    type="number"
    name="inputFirstNum" // Missing
    onChange={this.handleChange}
    value={this.state.inputFirstNum}
/>
<input
    type="number"
    name="inputLastNum" // Missing
    onChange={this.handleChange}
    value={this.state.inputLastNum}
/>

Next in your tests you're not passing the name property.

wrapper.find('input[type="number"]').at(0).simulate('change', {
    target: { 
        value: 111,
        name: 'inputFirstNum', // Missing
    },
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...