jeudi 28 janvier 2021

State is always default value when test with another value

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?

Aucun commentaire:

Enregistrer un commentaire