javascript - 如何触发模糊事件以使用 Enzyme 更改输入元素的值?
问题描述
我想为输入表单编写测试,但无法触发 Blur 事件。
我有一个包含以下输入元素的反应组件:
<input
id='email'
onBlur={this.handleInputChange}
name='email'
type='text'
/>
我还email
定义了状态和设置状态的函数:
handleInputChange = (event) => {
this.setState({ email: event.target.value });
};
我的测试文件中有以下内容:
const inputs = component.find('input');
expect(inputs.length).toEqual(2); // test case passes
inputs.at(0).simulate('blur', { target: { value: 'abc@hello' } });
expect(inputs.at(0).props().value).toEqual('abc@hello'); //test fails
如果我尝试模拟更改事件,测试也会失败:
inputs.at(0).simulate('change', { target: { value: 23 } });
在这两种情况下,我都会收到错误:
Expected: "abc@hello"
Received: undefined
看来我的代码没有触发该事件。谁能告诉我我做错了什么
解决方案
您在测试中引用了props().value
并且输入元素没有这样的属性。所以你需要在value
输入中添加道具
<input
id='email'
onBlur={this.handleInputChange}
name='email'
type='text'
value={this.state.email}
/>
为了测试预期的道具值,您需要强制重新渲染组件以反映新值。在 中Enzyme
,我们可以使用wrapper.setProps({})
. 您可以传递所需的值wrapper.setProps({value: 'abc@hello'})
或只是一个空对象,这里的目的是导致重新渲染。
const inputs = component.find('input');
expect(inputs.length).toEqual(2); // test case passes
inputs.at(0).simulate('blur', { target: { value: 'abc@hello' } });
// setProps should be called on the shallow or root wrapper.
component.setProps({}); // cause rerender.
expect(inputs.at(0).props().value).toEqual('abc@hello'); // test should pass
推荐阅读
- ios - 添加 Firebase In-AppMessaging 和 CloudMessaging 后 Appstore 上传被拒绝
- oracle - Oracle 数据库中的 JDBC 删除表、视图、函数过程
- kotlin - Kotlin 中的并发未来语法
- ios - 从 iOS swift 应用程序访问 Azure SQL 数据库表时出现问题
- javascript - 同一列上两个值的自定义排序器
- vb.net - 在 If 语句 Vb.net 中使用 return
- java - 递归调用订单插入方法对整个链表进行排序时遇到问题
- php - 如何生成动态 IF 语句
- ios - 在 UIScrollView 中仅水平缩放 UIView
- javascript - 在 Typescript 中扩展 Jquery