Testing a button with a method callback in a functional component

Viewed 276

I am trying to test a react component using Enzyme. I am not able to test the click on the IconButton component and the function doesn't get called when i simulate a click.

This is how IconButton is defined on an external component.

var IconButton = function (props) {
    return (React.createElement(IconButton$1, { color: 'default', onClick: props.onClick, disabled: props.disabled, size: props.size, onMouseDown: props.onMouseDown }, props.children));
};export{Button,IconButton};

This is how I am using it in my app.

import React, {useState, useEffect} from 'react';
import { Drawer } from '@material-ui/core';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { IconButton } from '@mycomponent/button';

export default function Component1 {
  const classes = useStyles();
  const [open, setOpen] = useState(true);

  const handleClick = function (event) {
    if (event) {
      setOpen(!open);
    }
    else {
      return;
    }
  };

  return (
    <Drawer>
      <div className="classname1">
          <IconButton onClick={(e) => handleClick(e)} className={classes.button, "iconBtn"}>
            {open ? <ExpandLessIcon data-test="lessIcon" /> : <ExpandMoreIcon data-test="moreIcon" />}
          </IconButton>
      </div>
    </Drawer>
  );
}

Here is my test for simulating the click on the Icon Button. I also tried another way to check that the handleClick was getting called but it still fails.

    const wrapper = shallow(<Component1 />);

    it('Test the button click', () => {
        expect(wrapper.containsMatchingElement(<ExpandMoreIcon />)).toBeTruthy()
        const element = wrapper.find(".iconBtn")
        const mockEvent = {target: {}};
        element.simulate('click', mockEvent)
        expect(wrapper.containsMatchingElement(<ExpandLessIcon />)).toBeTruthy()
    })
1 Answers

Try changing this line:

const element = wrapper.find("button").at(0);

or you could find it by it's className from debug():

const element = wrapper.find(".MuiButtonBase-root MuiIconButton-root");

Notice that you'd simulate a click on an actual html button in such case.

Related