我正在尝试测试表单中的输入字段。但是,当使用 Enzyme.js
来模拟
输入字段中的更改时,state
会错误地更新,因为日志显示 simulate
函数在名为 undefined
的状态下创建了新记录。我很乐意提供帮助。
问候
初始组件状态如下所示:
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
。)
关于reactjs - 使用 Enzyme.usestate 错误更新模拟输入更改时的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532449/