尝试在酶中测试FormControlLabel不会在模拟时触发点击

时间:2019-06-30 08:20:49

标签: reactjs material-ui enzyme

我正在尝试从材料UI测试FormControlLabel组件。 当我尝试模拟点击时,酶不会在我的组件上触发点击事件。

我尝试使用浅,createShallow,mount,createMount。

在调试中,我从find和findWhere查询中获取了组件,从外观上看,它具有包含所需复选框的控制道具。

我还尝试将取回的道具中的复选框用浅色和镶嵌物包裹起来,但它不起作用...

//parent.jsx
export public Parent = () => {
const [selected, setSelected] = useState(false);
const handleChange = (e,s) => {setSelected(s);};
...
return (
...
    <FormControlLabel control={
        <Checkbox onChange={handleChange} 
                checked={selected}}
label='some label'/>
...
);
}


//test.js
...
let component = createMount()(<Parent/>);

let checkbox = component.find(FormControlLabel)
.findWhere(c=>c.prop('label')==='some label').first();

checkbox.simulate('click');
checkbox.simulate('change');

//rest of the test
//the function handleChange is not called in debug.

预期:

  • 模拟点击或更改应调用onChange函数

实际:

  • 更改不会被触发

代码有效,测试无效。

请帮助!

2 个答案:

答案 0 :(得分:2)

尝试一下

let checkbox = component.find(FormControlLabel);
checkbox.prop('control').props.onChange({ target: { checked: true }, persist: jest.fn() });

使用浅层为我工作。

答案 1 :(得分:1)

诀窍是构造一个具有checked : true字段的事件。

修改代码:

let checkbox = component.find(FormControlLabel).findWhere(c=>c.prop('label')==='some label').first();
// Wrap the control prop.
enzyme.shallow(checkbox.prop('control')).simulate('change', { target : { checked : true }} );