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?
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: