Testing onClose event from a component to be called using jest

纵饮孤独 提交于 2019-12-11 17:01:32

问题


I am doing tests for a react component using jest and enzyme and haven't figured out how to test the onClose event from the material-ui Menu. Same should apply to other components but we can stick with the Menu for the sake of this question. Here it is my component:

import { Menu, MenuItem } from "@material-ui/core";

export class ItemPreviewerPage extends React.Component<ComponentProps, ComponentState> {
  constructor(props) {
    super(props);
    this.state = {
        anchorEl: undefined,
        fieldsetMenu: undefined,
        isColumnSelectorOpen: false,
    };
  }

  render() {
    const { classes } = this.props;
    const moreMenuOpen = Boolean(this.state.anchorEl);

    return (
        <Menu className={classes.cardMenu}
              id="long-menu"
              anchorEl={this.state.anchorEl}
              open={moreMenuOpen}
              onClose={() => this.handleClose()}
              PaperProps={{
                style: {
                    maxHeight: 48 * 4.5,
                    width: 200
                }
               }}>
        </Menu>
    );
  }
}

and for the test, I was expecting the Menu to be closed if I set the state of the anchorEl to true and then to false.

it("Calls the handleClose when the Menu is closed", () => {
    const props = initialProps;

    const wrapper = shallow(<ItemPreviewerPage {...props} />);
    const spy = jest.spyOn(wrapper.instance(), "handleClose");

    wrapper.setState({ anchorEl: true });
    wrapper.instance().forceUpdate();        
    wrapper.setState({ anchorEl: false });
    wrapper.instance().forceUpdate();

    expect(spy).toBeCalled();
});

What's wrong? How can I test the onClose?


回答1:


I figured out how to test it. The setState doesn't affect the behaviour directly, I needed to use the simulate function with the close argument:

it("Calls handleClose when menu is closed", () => {
    const props = initialProps;
    const tree = shallow(<ItemPreviewerPage {...props} />);
    tree.find(Menu).simulate("close");
    expect(props.handleClose).toBeCalled();
});


来源:https://stackoverflow.com/questions/52778329/testing-onclose-event-from-a-component-to-be-called-using-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!