简体   繁体   English

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

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

I am using Material-UI with react to build a Dropdown component.我正在使用 Material-UI 和 react 来构建一个Dropdown组件。

Dropdown.tsx下拉列表.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>
  );
}

I am now testing this component using react-testing-library.我现在正在使用 react-testing-library 测试这个组件。 I want to check that the 2nd option in the dropdown is disabled.我想检查下拉菜单中的第二个选项是否被禁用。 I tried checking that the onSearch function which is called on click of the menuitem is not called when I click the 2nd option.我尝试检查在单击第二个选项时未调用在单击菜单项时调用的 onSearch function。

test to check option is disabled测试检查选项被禁用

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

But this did not work.但这没有用。 The function is being called once. function 被调用一次。 Why is this happening and how can I test what I want to test?为什么会发生这种情况,我该如何测试我想要测试的内容?

I am using Material-UI with react to build a Dropdown component.我正在使用 Material-UI 和 react 来构建一个Dropdown组件。

Dropdown.tsx下拉列表.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>
  );
}

I am now testing this component using react-testing-library.我现在正在使用 react-testing-library 测试这个组件。 I want to check that the 2nd option in the dropdown is disabled.我想检查下拉列表中的第二个选项是否被禁用。 I tried checking that the onSearch function which is called on click of the menuitem is not called when I click the 2nd option.我尝试检查在单击第二个选项时未调用在单击菜单项时调用的 onSearch 函数。

test to check option is disabled测试检查选项被禁用

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

But this did not work.但这不起作用。 The function is being called once.该函数被调用一次。 Why is this happening and how can I test what I want to test?为什么会发生这种情况,我该如何测试要测试的内容?

I am using RTL with Jest and This work for me.我正在使用带有 Jest 的 RTL,这对我有用。

const menuitem = screen.getAllByRole('menuitem', { name: 'manue-item-name' });
screen.debug(menuitem);
expect(menuitem[0].getAttribute('aria-disabled')).toBeTruthy();

OR或者

const menuitem = screen.getAllByRole('menuitem');
screen.debug(menuitem);
expect(menuitem[0].getAttribute('aria-disabled')).toBeTruthy();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用react-testing-library测试withStyles中包含的样式化的Material-UI组件? - How to test styled Material-UI components wrapped in withStyles using react-testing-library? 使用 react-testing-library 测试 material-ui 数据网格时出现问题 - Problem testing material-ui datagrid with react-testing-library 反应测试库 material-ui slider - react-testing-library material-ui slider 使用带有 material-ui 的 react-testing-library 的问题 - issue working with react-testing-library with material-ui 反应。 Fromik。 Material-ui表单提交事件测试使用react-testing-library失败 - React. Fromik. Material-ui form submit event testing fails using react-testing-library 检查按钮是否在 react-testing-library 中被禁用 - Check that button is disabled in react-testing-library react-testing-library + material-ui 错误:元素类型无效: - react-testing-library + material-ui error: Element type is invalid: 如何使用 react-testing-library 测试材质 ui MenuList 组件上的按键按下事件 - How to test key down event on material ui MenuList component using react-testing-library 在使用 react-testing-library 进行测试期间,单击两次 material-ui 图标不会将其颜色更改为默认值 - Clicking twice material-ui icon does not change its color to default during tests with react-testing-library 如何在 React 测试库中获取 Material-UI 密码输入 - How to get a Material-UI password input in React Testing Library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM