I'm testing a react Material UI Menu component using react-testing-library with an onClose
prop that is triggered when the menu loses focus. I cannot trigger this state though even when I add a click to a component outside of the menu or a focus an input element outside.
const UserMenu: React.FunctionComponent<UserMenuProps> = ({ className }) => {
const signedIn = useAuthState(selectors => selectors.SignedIn);
const username = useAuthState(selectors => selectors.Username);
const messages = useMapState((state: AppRootState) => state.app.messages);
const signOut = useSignOut();
const [open, updateOpenStatus] = useState(false);
const anchorRef = useRef(null);
if (!signedIn) {
return <div data-testid="user-menu" className={className}>
<LinkButton to={ROUTES.SignIn.link()}>{messages.SignIn.Title}</LinkButton>
<LinkButton to={ROUTES.SignUp.link()}>{messages.SignUp.Title}</LinkButton>
<LinkButton to={ROUTES.ConfirmSignUp.link()}>{messages.ConfirmSignUp.Title}</LinkButton>
</div>;
}
return <div data-testid="user-menu" className={className}>
<Grid container direction="row" alignItems="center">
<Typography noWrap variant="subtitle2">
<span id="username" className="bold">{username}</span>
</Typography>
<IconButton id="menu-toggle" buttonRef={anchorRef} onClick={() => updateOpenStatus(true)}>
<AccountCircle/>
</IconButton>
<Menu
anchorEl={anchorRef.current}
anchorOrigin={{
vertical: 'top',
horizontal: 'right'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right'
}}
open={open}
onClose={() => updateOpenStatus(false)}
>
<MenuItem id="sign-out" onClick={() => { updateOpenStatus(false); signOut(); }}>{messages.SignOut.Action}</MenuItem>
</Menu>
</Grid>
</div>;
};
Test code
it('should open and close menu', async () => {
const { getByTestId } = render(<><UserMenu/>
<input data-testid="other"/>
</>, { state });
fireEvent.click(getByTestId('menu-toggle'));
expect(MockMenu).toHaveBeenLastCalledWith(expect.objectContaining({ open: true }), {});
fireEvent.focus(getByTestId('other'));
expect(MockMenu).toHaveBeenLastCalledWith(expect.objectContaining({ open: false }), {});
});
I've also tried fireEvent.click(getByTestId('other'));
without success.
This question for enzyme has a solution by using tree.find(Menu).simulate("close");
, but I don't think that's possible with react-testing-library
.
getByTestId('menu-toggle')
but you don't have anydata-testid="menu-toggle"
– Foe