jeudi 30 avril 2020

How to toggle and check a Material UI Checkbox in Enzyme / Jest Test

I've got a simple component wrapped around a Material UI Checkbox. I've stripped it down to the bare minimum here.

//@flow
import React from "react";
import { Checkbox } from "@material-ui/core";

function MyCheckboxComponent() {
  const [checkedState, setCheckedState] = React.useState(true);

  const handleChange = event => {
    setCheckedState(event.target.checked);
  };

  return <Checkbox checked={checkedState} onChange={handleChange} />;
}

export default MyCheckboxComponent;

I simply want to test this component and toggle the Checkbox value and check it. I cannot get my simple test passing. I'm at a loss as to why.

import React from "react";

import Enzyme, { mount } from "enzyme";
import { Checkbox } from "@material-ui/core";
import Adapter from "enzyme-adapter-react-16";

import MyCheckboxComponent from "./MyCheckboxComponent";
Enzyme.configure({ adapter: new Adapter() });

/** Interaction tests testing user interaction with PilzButton */
test("Toggle Checkbox test", () => {
  const wrapper = mount(<MyCheckboxComponent />);

  const checkBox = wrapper.find(Checkbox);
  expect(checkBox).toHaveLength(1);

  checkBox.simulate('change', { target: { checked: true } });

  expect(checkBox.props().checked).toBe(true);
});

Should checkBox.simulate('change', { target: { checked: true } }); work and toggle the value of the Checkbox ??

What I have so far is here on CodeSandbox ...

Edit toggle-material-ui-checkbox-jest




Aucun commentaire:

Enregistrer un commentaire