首页 > 解决方案 > 如何模拟从 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 元素,但这没有任何作用。

从下拉列表中模拟选择的正确方法是什么?

标签: reactjsjestjsenzyme

解决方案


您可以触发更改事件,因为您有this.handlechange触发器onChange

const component = mount(<MyComponent/>);
component.find('#dropdown').at(0).simulate('change', {
    target: { value: 'item1', name: 'item1' }
});

我会说您必须添加.at(0),因为即使您只有一个具有该 ID 的元素,Enzyme 也会找到一个值列表。


推荐阅读