3
votes

I am trying to test a FormControlLabel component from material UI. When I try to simulate click Enzyme won't fire a click event on my component.

I tried using shallow, createShallow, mount, createMount.

In debug I get the component from the find and findWhere query and by the looks of it it has a props of control that contains the wanted checkbox.

I also tried to wrap the checkbox from the retrieved props with shallow and mount and it didn't work...

//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.

Expected:

  • simulate click or change should call the onChange function

Actual:

  • change won't be triggered

the code works, the test dont.

please help!!!

2

2 Answers

4
votes

Try this

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

Worked for me using shallow.

1
votes

The trick is to construct an event that has a checked : true field.

modifying your code:

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 }} );