试图测试反应组分形式的变化函数

时间:2017-12-09 11:47:03

标签: javascript reactjs

所以我有一个Signup组件,它使用简单的文本字段和提交函数呈现一个表单。在字段中输入文本时,地址为'属性应该更新。在我的测试中,我试图断言onChange函数被调用但是使用jest来存根函数。但是,当我尝试模拟更改时,我收到错误:

TypeError: result.simulate(...) is not a function

如果我删除了.bind(this),它就会在函数中设置状态,但这是未定义的。

这是我的代码:

import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
  }

  render() {
    return (
      <div>
      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>
      </div>
    );
  }
}

export default Signup;

我的测试:

test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy"
    const onChange = jest.fn()
    const wrapper = shallow(<Signup onChange={onChange} />)
    const result = wrapper.find('#address')
    result.simulate('change', { target: { value: {value} } })('change');
    expect(onChange.called).toBe.true
  })

1 个答案:

答案 0 :(得分:0)

您从onChange尝试props的间谍,但在您的组件中没有任何道具。
组件的方法和组件道具是不同的东西 您需要在this.props.onChange内拨打this.onChange

import React, { Component } from 'react';

class Signup extends Component {

  constructor(props){
    super(props);
    this.state = {};
  }

  onSubmit(e){
    let {address} = this.state;
    this.setState({
      address: ""
    });
    this.props.addFeed(address);
    e.preventDefault();
  }
  onChange(e) {
      this.setState({
        address: e.target.value
      });
      // Call onChange callback
      this.props.onChange();
  }

  render() {
    return (
      <div>
      <form onSubmit={this.onSubmit.bind(this)}>
        Please enter your address:
        <input id='address' type="text" onChange={this.onChange.bind(this)} value={this.state.address}>
        </input>
        <input type="submit" value="Submit">
        </input>
      </form>
      </div>
    );
  }
}

还有一些修复你的测试

test("onChange() is called upon changing the text field", () => {
    const value = "Makers Academy";
    const onChange = jest.fn();
    const wrapper = shallow(<Signup onChange={onChange} />);
    const result = wrapper.find('#address');
    result.simulate('change', {target: {value}});
    expect(onChange.called).toBe(true);
});