reactjs - 使用 Enzyme.js 模拟输入更改时出现错误 - 状态不正确更新
问题描述
我正在尝试测试表单中的输入字段。但是,当Enzyme.js
用于simulate
更改输入字段时,state
会错误地更新,因为日志显示该simulate
函数已在名为undefined
.I 的状态下创建了新记录。我非常乐意提供帮助。
问候
初始组件状态如下所示:
this.state = {
submission: {
firstName: '',
lastName: '',
email: '',
date: new Date(),
validation: {
email : {isInvalid: false, message: ""},
firstName : {isInvalid: false, message: ""},
isValid : true,
lastName : {isInvalid: false, message: ""}
}
}
}
这是测试功能:
it('should respond to change event and change the state of the Component', () =>{
const wrapper = shallow(<ApplicationForm/>);
console.log(wrapper.find('#firstName').debug());
wrapper.find('#firstName').simulate(
'change', {
target: {
name: 'firstName',
value: 'John'
}
}
)
expect(wrapper.state().submission.firstName).to.equal('John');
})
这是我期望的状态:
submission: {
firstName: 'John',
...
}
这就是我检查结果时得到的结果debug
submission: {
firstName: '',
lastName: '',
email: '',
date: new Date(),
validation: {
email : {isInvalid: false, message: ""},
firstName : {isInvalid: false, message: ""},
isValid : true,
lastName : {isInvalid: false, message: ""}
},
undefined: 'John'
}
下面你可以看到渲染表单的代码:
<input type="text"
id="firstName"
className="form-control form-control-sm"
placeholder="First name"
onChange={this.updateSubmission.bind(this)}
/>
updateSubmission 函数如下所示:
updateSubmission(event) {
let updatedSubmission = Object.assign({}, this.state.submission);
updatedSubmission[event.target.id] = event.target.value;
this.setState({
submission: updatedSubmission
});
}
解决方案
updateSubmission
处理程序使用target.id
:
updatedSubmission[event.target.id] = event.target.value;
但在您使用的测试中name
:
target: {
name: 'firstName',
value: 'John'
}
修复要使用的测试target
对象id: 'firstName'
应该修复它。(或者您可以切换到name
在您的代码中使用。)
推荐阅读
- c++ - 将内存预分配给对齐的字节,如 c 或 c++ 中的对齐分配
- javascript - 仅在来自 axios 的请求的循环完成后才执行代码块
- ubuntu-18.04 - Zabbix代理无法连接到Zabbix5.0服务器
- c - 为结构内的变量动态分配内存,如 int、double 等
- c# - Xamarin.Forms ImageCell 不显示图像版本 4.7.0.xx
- css - 为什么grid-gap会导致没有百分比的溢出?
- javascript - 第一个 JavaScript 参数是否可能具有默认值?
- python - TypeError:Python Spacy-Stopword NLP 中需要一个整数
- firebase - 使用 Firebase Cloud Function 解析本地 .CSV 文件?
- html - 图像叠加悬停“指针事件:无;” 在 WordPress 中不起作用?