gpt4 book ai didi

reactjs - 如何使用react-testing-library为react ui Menu触发onClose?

转载 作者:行者123 更新时间:2023-12-04 02:51:00 25 4
gpt4 key购买 nike

我正在使用带有 onClose 的 react-testing-library 测试 react Material UI Menu 组件当菜单失去焦点时触发的 Prop 。即使我向菜单外的组件添加单击或将输入元素放在外时,我也无法触发此状态。

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 }), {});
});

我也试过 fireEvent.click(getByTestId('other'));没有成功。

question对于 enzyme 有一个解决方案,使用 tree.find(Menu).simulate("close"); ,但我认为这是不可能的 react-testing-library .

最佳答案

您可以通过单击菜单生成的背景来触发关闭。我发现最简单的方法是通过 getByRole('presentation') 选择背景。 @testing-library的方法.

测试代码:

it('should open and close the menu', () => {
const { getByTestId, getByRole } = render(<UserMenu />);

fireEvent.click(getByTestId('menu-toggle'));

// Get the backdrop, then get the firstChild because this is where the event listener is attached
fireEvent.click(getByRole('presentation').firstChild));

expect(MockMenu).toHaveBeenLastCalledWith(expect.objectContaining({ open: false }), {});
});

关于reactjs - 如何使用react-testing-library为react ui Menu触发onClose?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com