samedi 17 octobre 2020

How to Test Material-ui RadioGroup button Change with Jest Enzyme

How do I test Material-ui RadioGroup button changes and the subsequent change of RadioGroup prop 'value' which is set to a local state(useState) value

On change event should fire handleChange which I have mocked

describe("test", () => {
  test(`radio`, () => {

    const handleChange = jest.fn();
    const component = shallow(
      <App />
    );
    const radioGroup = component.find(`[data-test="colorGroup"]`).at(0);
    const blueRadio = radioGroup.find(`[label="blue"]`).at(0);
    blueRadio.simulate(`click`, { checked: true });

    expect(handleChange.mock.calls.length).toBe(1);
  });
});

App component

export const App = () => {
  const [color, setColor] = useState(`default`);

  const handleOnChange = (event) => setColor(event.target.value);
  return (
    <Accordion  elevation={0}>
      <AccordionSummary
        expandIcon={<ExpandMoreIcon />}
        aria-controls="panel1a-content"
        id="panel1a-header"
      >
        <Typography>choose color</Typography>
      </AccordionSummary>
      <AccordionDetails>
        <FormControl component="fieldset">
          <RadioGroup
            row
            onChange={handleOnChange}
            value={color}
            name="position"
            data-test={`colorGroup`}
          >
            <FormControlLabel
              value="default"
              control={<Radio color="primary" />}
  
            />
            <FormControlLabel
              value="blue"
              control={<Radio color="primary" />}
              label="blue"
            />
          </RadioGroup>
        </FormControl>
      </AccordionDetails>
    </Accordion>
  );
};

test files are in component/ home.spect.js https://codesandbox.io/s/sample-testing-in-react-using-jest-and-enzyme-forked-rrrct?fontsize=14&hidenavigation=1&theme=dark

Aucun commentaire:

Enregistrer un commentaire