【发布时间】:2017-12-09 11:47:03
【问题描述】:
所以我有一个 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
})
【问题讨论】:
标签: javascript reactjs