the problem is pretty straightforward. I have a material-ui menu I would like to test closes appropriately (through a user clicking outside of the menu).
This has proven to be quite challenging. Here's the component (ripped right from the the docs):
class App extends React.Component {
state = {
anchorEl: null
};
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { anchorEl } = this.state;
return (
<div>
<Typography variant="body1"> Click Me</Typography>
<Button
aria-owns={anchorEl ? "simple-menu" : undefined}
aria-haspopup="true"
onClick={this.handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
}
And the tests:
const props = {
classes: {}
};
describe("test", () => {
it("closes the menu", () => {
const wrapper = mount(<App {...props} />);
wrapper.find(Button).simulate("click");
expect(wrapper.find(Menu).prop("open")).toBe(true);
wrapper.find(Typography).simulate("click");
expect(wrapper.find(Menu).prop("open")).toBe(false);
wrapper.unmount();
});
it("closes the menu a different way", () => {
const outerNode = document.createElement("div");
outerNode.setAttribute("id", "root-node");
document.body.appendChild(outerNode);
const wrapper = mount(<App {...props} />, {
attachTo: outerNode
});
wrapper.find(Button).simulate("click");
expect(wrapper.find(Menu).prop("open")).toBe(true);
outerNode.click();
expect(wrapper.find(Menu).prop("open")).toBe(false);
wrapper.unmount();
});
it("closes the menu yet a different way", () => {
const eventMap = {};
window.addEventListener = jest.fn((event, cb) => {
eventMap[event] = cb;
});
const wrapper = mount(<App {...props} />);
wrapper.find(Button).simulate("click");
expect(wrapper.find(Menu).prop("open")).toBe(true);
wrapper.find(Typography).simulate("click");
eventMap.click();
expect(wrapper.find(Menu).prop("open")).toBe(false);
wrapper.unmount();
});
});
None of these tests work, unfortunately. I was doing some digging and came across this SO post which links this github issue where the solutions and third approaches originally came from, however, I can't get any of these to work.
I created a CodeSandbox with the code below for any kind generous souls here who desire to help.