reactjs - 如何模拟从 Jest / 酶测试中的下拉列表中选择?
问题描述
我正在尝试为具有如下下拉列表的 React 组件编写开玩笑测试:
<select id="dropdown" onChange={this.handlechange} ref={this.refDropdown}>
{this.props.items.map(item => {
return (
<option key={item.id} value={item.id}>
{item.name}
</option>
);
})}
</select>
处理程序如下所示:
handlechange = () => {
const sel = this.refDropdown.current;
const value = sel.options[sel.selectedIndex].value;
//...
}
我想模拟用户在列表中选择第二个条目(或除第一个之外的任何条目)但遇到问题。如果我模拟“更改”事件,它会触发调用,handlechange()
但selectedIndex
始终设置为零。
我在开玩笑的测试中尝试了这段代码,但它不会导致selectedIndex
在处理程序中可以访问。
const component = mount(<MyComponent/>);
component.find("#dropdown").simulate("change", {
target: { value: "item1", selectedIndex: 1 }
});
发生的事情几乎是正确的。如果我查看传入的事件,我可以看到e.value
设置为“item1”,但它不像实际进行了选择。
我也尝试尝试直接将“点击”模拟发送到 Option 元素,但这没有任何作用。
从下拉列表中模拟选择的正确方法是什么?
解决方案
您可以触发更改事件,因为您有this.handlechange
触发器onChange
:
const component = mount(<MyComponent/>);
component.find('#dropdown').at(0).simulate('change', {
target: { value: 'item1', name: 'item1' }
});
我会说您必须添加.at(0)
,因为即使您只有一个具有该 ID 的元素,Enzyme 也会找到一个值列表。
推荐阅读
- python - pytest - 模拟配置[
] 通过 configparser.ConfigParser() / config.read() - mysql - 为什么 NOT NULL DEFAULT current_timestamp() 在创建此表时会给出错误 Invalid default value?
- api - 如何在 laravel 8 api 中使用外键获取、插入和更新数据
- c# - 比较一系列两个变量的最简洁方法?
- javascript - Object.defineProperty 不更改键顺序
- c# - 在 .NET 5 中,有没有办法提前将代码编译成二进制文件并仅剥离 IL(而不是反射数据)?
- javascript - Javascript:如何通过触摸选择文本并防止拖动屏幕
- javascript - 按最新的优先顺序订购 Firestore 文档
- javascript - 按行在html上显示数组值
- python - “转到定义”选项在 Visual Studio Code 中不起作用