物料UI选择onChange在反应测试库中不起作用

时间:2020-07-08 22:58:30

标签: reactjs jestjs material-ui react-testing-library

<Select
                    inputProps={{ "data-testid": "change-form" }}
                    multiple
                    value={permissionsArr}
                    onChange={handleChange}
                    input={<Input />}
                    renderValue={selected => (
                        <ChipsContainer >
                            { selected.map(value => (
                                <Chip key={value} label={value} />
                            ))}
                        </ChipsContainer >
                    )}
                >
                    {perms.map(name => (
                        <MenuItem key={name} value={name}>{prettyName(name)}</MenuItem>
                    ))}
                </Select>

这是我要测试的选择元素,在这里,permissionArr是显示的字符串的列表。并且handleChange正在更改PermissionsArr。但是当我尝试测试时:

const labelPermissions = queryByTestId("change-form")
fireEvent.change(labelPermissions, { target: { value:  ["string", "string"] }} );

它不调用onChange事件。可能是因为值不应该是数组是我的最佳猜测。我已经坚持了一段时间,将不胜感激。

1 个答案:

答案 0 :(得分:1)

Select确实没有change事件。当由于其他事件而发生更改时,通常会单击onChange来调用提供给MenuItem的函数。我建议您将测试的结构设计为使用与用户相同的交互方式。

以下是使用documentation中的多重选择的示例测试:

demo.test.js

import React from "react";
import {
  render,
  fireEvent,
  waitForElementToBeRemoved,
  screen
} from "@testing-library/react";
import Demo from "./demo";
import "@testing-library/jest-dom/extend-expect";

test("display and change select", async () => {
  render(<Demo />);
  // Open the Select
  fireEvent.mouseDown(screen.getByLabelText("Name"));
  // Click the entries you want to select
  fireEvent.click(screen.getByText("Van Henry"));
  fireEvent.click(screen.getByText("April Tucker"));
  // Close the select using Escape or Tab or clicking away
  fireEvent.keyDown(document.activeElement, {
    key: "Escape",
    code: "Escape"
  });
  // Wait for Menu to close
  await waitForElementToBeRemoved(screen.getByText("Oliver Hansen"));
  // Verify selections
  expect(screen.getByLabelText("Name")).toHaveTextContent(
    "Van Henry, April Tucker"
  );
});

这是正在测试的代码:

demo.js

import React from "react";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import Input from "@material-ui/core/Input";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120,
    maxWidth: 300
  },
  chips: {
    display: "flex",
    flexWrap: "wrap"
  },
  chip: {
    margin: 2
  },
  noLabel: {
    marginTop: theme.spacing(3)
  }
}));

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250
    }
  }
};

const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder"
];

function getStyles(name, personName, theme) {
  return {
    fontWeight:
      personName.indexOf(name) === -1
        ? theme.typography.fontWeightRegular
        : theme.typography.fontWeightMedium
  };
}

export default function MultipleSelect() {
  const classes = useStyles();
  const theme = useTheme();
  const [personName, setPersonName] = React.useState([]);

  const handleChange = event => {
    setPersonName(event.target.value);
  };

  return (
    <div>
      <FormControl className={classes.formControl}>
        <InputLabel id="demo-multiple-name-label">Name</InputLabel>
        <Select
          labelId="demo-multiple-name-label"
          id="demo-multiple-name"
          multiple
          value={personName}
          onChange={handleChange}
          input={<Input />}
          MenuProps={MenuProps}
        >
          {names.map(name => (
            <MenuItem
              key={name}
              value={name}
              style={getStyles(name, personName, theme)}
            >
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Edit Select change test