小编Alw*_*ing的帖子

如何模拟从 Jest/酶测试中的下拉列表中选择?

我正在尝试为我的 React 组件编写 Jest 测试,该组件具有如下下拉列表:

<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>
Run Code Online (Sandbox Code Playgroud)

处理程序如下所示:

handlechange = () => {
    const sel = this.refDropdown.current;
    const value = sel.options[sel.selectedIndex].value;
    //...
}
Run Code Online (Sandbox Code Playgroud)

我想模拟用户选择列表中的第二个条目(或第一个条目以外的任何条目)但遇到问题。如果我模拟一个“更改”事件,它会触发调用,handlechange()selectedIndex始终设置为零。

我在 jest 测试中尝试了这段代码,但它不会导致selectedIndex在处理程序中可以访问。

const component = mount(<MyComponent/>);
component.find("#dropdown").simulate("change", {
    target: { value: "item1", selectedIndex: 1 }
});
Run Code Online (Sandbox Code Playgroud)

发生的事情几乎是正确的。如果我查看传入的事件,我可以看到e.value设置为“item1”,但它并不像实际做出的选择一样。

我还尝试将“点击”模拟直接发送到 Option 元素,但这没有任何作用。

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

reactjs jestjs enzyme

7
推荐指数
2
解决办法
2万
查看次数

标签 统计

enzyme ×1

jestjs ×1

reactjs ×1