因此,我有一个注册组件,该组件具有简单的文本字段并提交功能。在字段中输入文本时,应更新"地址"属性。在我的测试中,我试图断言onchange功能被称为,但使用开玩笑将功能固定。但是,当我尝试模拟更改时,我会收到错误:
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
})
您尝试从 props
尝试 onChange
,但在您的组件中没有任何道具。
组件的方法和组件道具是不同的东西。
您需要在this.onChange
中致电this.props.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);
});