3

我正在使用 react-testing-library 测试一个 react Material UI Menu 组件,该组件带有一个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 }), {});
    });

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

酶的这个问题有一个解决方案tree.find(Menu).simulate("close");,但我认为这是不可能的react-testing-library

4

2 回答 2

6

您可以通过单击菜单生成的背景来触发关闭。我发现最简单的方法是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 }), {});
});
于 2020-02-22T01:17:19.623 回答
0

@testing-library/user-event用来触发esc新闻。

import {
  render,
  screen,
  waitFor,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('should open and close the menu', async () => {
  render(<UserMenu />);

  // Click to open
  userEvent.click(
    // Note that grabbing by test id is frowned upon if there are other ways to grab it https://testing-library.com/docs/queries/about/#priority
    screen.getByTestId('menu-toggle')
  );

  // Wait for dialog to open
  await waitFor(() => expect(MockMenu).toHaveBeenLastCalledWith(expect.objectContaining({ open: true }), {}));

  // Press `esc` to close
  userEvent.keyboard('{esc}');

  // Wait for dialog to close
  await waitFor(() => expect(MockMenu).toHaveBeenLastCalledWith(expect.objectContaining({ open: false }), {}));
});
于 2022-02-28T18:52:58.230 回答