我正在使用带有uwsgi
道具的react-testing-library测试react Material UI菜单组件,当菜单失去焦点时会触发该道具。即使我在菜单外的组件中添加单击或将输入元素聚焦在外部,也无法触发此状态。
onClose
测试代码
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>;
};
我也尝试过 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 }), {});
});
,但没有成功。
这种question的酶可以通过使用fireEvent.click(getByTestId('other'));
来解决,但我不是用react-testing-library来实现的。
答案 0 :(得分:3)
您可以通过单击菜单生成的背景来触发关闭。我发现最简单的方法是通过getByRole('presentation')
的{{1}}方法选择背景。
测试代码:
@testing-library