【问题标题】:Trying to test FormControlLabel in enzyme won't trigger click when simulate模拟时尝试在酶中测试 FormControlLabel 不会触发点击
【发布时间】:2019-11-11 09:18:26
【问题描述】:

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

我尝试过使用 shallow、createShallow、mount、createMount。

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

我还尝试使用 shallow 和 mount 将检索到的 props 中的复选框包装起来,但它不起作用......

//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函数

实际:

  • 不会触发更改

代码有效,测试无效。

请帮忙!!!

【问题讨论】:

    标签: reactjs material-ui enzyme


    【解决方案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 }} );
    

    【讨论】:

      【解决方案2】:

      试试这个

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

      使用浅层为我工作。

      【讨论】:

      • 另外,如果控制道具有多个组件包裹在片段中,那么需要找到这样的道具:.props.children[0].props 等...
      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2018-03-30
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多