如何使用 react-testing-library 检查 material-ui MenuItem 是否被禁用

How to check if a material-ui MenuItem is disabled using react-testing-library

我正在使用 Material-UI 和 React 来构建一个 Dropdown 组件。

Dropdown.tsx

import React from "react";
import ClickAwayListener from "@material-ui/core/ClickAwayListener";
import Grow, { GrowProps } from "@material-ui/core/Grow";
import Input from "@material-ui/core/Input";
import MenuList from "@material-ui/core/MenuList";
import Paper from "@material-ui/core/Paper";
import Popper from "@material-ui/core/Popper";
import MenuItem from "@material-ui/core/MenuItem";

export default function Dropdown(props: {
  onSearch: (suggestion: string) => void;
}) {
  const [searchText, setSearchText] = React.useState("");
  const [open, setOpen] = React.useState(false);

  let searchElement: null | HTMLElement = null;

  const onSearchTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(event.target.value);
    setOpen(true);
  };

  const openSearchSuggestion = () => {
    setOpen(true);
  };

  const setSearchElement = (node: null | HTMLElement) => {
    searchElement = node;
  };

  const closeSearchSuggestion = () => {
    setOpen(false);
  };

  const handleOnClickAway = (event: React.MouseEvent<EventTarget>) => {
    if (searchElement && searchElement.contains(event.target as HTMLElement)) {
      return;
    }
    closeSearchSuggestion();
  };

  const handleSearchSuggestionClick = (suggestion: string) => (
    event: React.MouseEvent<EventTarget>
  ) => {
    props.onSearch(suggestion);
  };

  const searchSuggestionsRenderer = (suggestion: string, index: number) => {
    return (
      <MenuItem
        key={index}
        onClick={handleSearchSuggestionClick(suggestion)}
        className="suggestion-item"
        id={`suggestion-item-${index}`}
        disabled={suggestion === "Criteria 2"}
      >
        {searchText} in {suggestion}
      </MenuItem>
    );
  };

  const popperTrans = ({ TransitionProps }: { TransitionProps: GrowProps }) => {
    const searchSuggestions = ["Criteria 1", "Criteria 2"];
    return (
      <Grow {...TransitionProps} style={{ transformOrigin: "0 0 0" }}>
        <Paper className="search-suggestions-paper">
          <ClickAwayListener onClickAway={handleOnClickAway}>
            <MenuList>
              {searchText &&
                searchSuggestions &&
                searchSuggestions.map(searchSuggestionsRenderer)}
            </MenuList>
          </ClickAwayListener>
        </Paper>
      </Grow>
    );
  };

  return (
    <div>
      <Input
        inputRef={setSearchElement}
        className="search-input"
        placeholder="Search"
        value={searchText}
        onChange={onSearchTextChange}
        onFocus={openSearchSuggestion}
        data-testid="searchInput"
      />
      <Popper
        className="search-suggestion-popper"
        open={open && searchText.trim().length >= 2}
        anchorEl={searchElement}
        placement="bottom-start"
        transition={true}
      >
        {popperTrans}
      </Popper>
    </div>
  );
}

我现在正在使用 react-testing-library 测试这个组件。我想检查下拉列表中的第二个选项是否被禁用。我尝试检查单击第二个选项时是否调用了单击菜单项时调用的 onSearch 函数。

测试以检查选项是否被禁用

  test('that criteria 2 option is disabled', () => {
    const props = { onSearch: jest.fn() }
    const { getAllByRole, getByTestId } = render(<Dropdown {...props} />);
    const Input = getByTestId('searchInput');
    const TextBox = globalGetByRole(Input, 'textbox') as HTMLInputElement;
    fireEvent.change(TextBox, { target: { value: 'test' } });
    const MenuItems = getAllByRole('menuitem');
    expect(MenuItems.length).toBe(2);
    const Criteria2MenuItem = MenuItems[1];
    fireEvent.click(Criteria2MenuItem);
    expect(props.onSearch).toHaveBeenCalledTimes(0);
  });

但这没有用。该函数被调用一次。为什么会发生这种情况,我该如何测试我想测试的内容?

当您禁用 Material-UI MenuItem 例如

<MenuItem disabled>
 {...}
</MenuItem>

它将aria-disabled="true"Mui-disabledCSSclass添加到DOM中的li元素。 li 不是有效按钮,因此您无法通过单击它来测试它。您需要使用 jest-dom.

中的 .toHaveAttribute() 检查它是否具有 aria-disabled 属性
expect(Criteria2MenuItem).toHaveAttribute("aria-disabled")