如何使用 React 测试库测试 Material UI 选择组件

hru*_*lok 8 testing reactjs material-ui react-testing-library

我正在使用反应测试库进行组件测试。材质 UI 选择选项在弹出窗口中呈现。调试不列出选项。在选择选项的情况下如何触发点击事件。

以下是我选择的组件。

import TextField from '@material-ui/core/TextField';
import { MenuItem } from '@material-ui/core';

<TextField
  select
  id="fruit"
  inputProps={{ id: "fruit" }}
  SelectProps={{
    SelectDisplayProps: {
      'data-testid': "fruit"
    }
  }}
  fullWidth
  variant="outlined"
  {...errors}
>
  {options.map(option => (
    <MenuItem key={option[valueFieldName]} value={option[valueFieldName]}>
      {option[labelFieldName]}
    </MenuItem>
  ))}
</TextField>
Run Code Online (Sandbox Code Playgroud)

什么查询选择器应该用于 onclick 事件。

这是 debug() 记录该字段的方式

    <div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth">
  <label
    class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-outlined"
    data-shrink="false"
    for="fruit"
    id="fruit-label"
  >
    Action on failure
  </label>
  <div class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-fullWidth MuiInputBase-formControl">
    <div
      aria-haspopup="listbox"
      aria-labelledby="fruit-label fruit"
      class="MuiSelect-root MuiSelect-select MuiSelect-selectMenu MuiSelect-outlined MuiInputBase-input MuiOutlinedInput-input"
      data-testid="fruit"
      id="fruit"
      role="button"
      tabindex="0"
    >
      <span>?</span>
    </div>
    <input name="fruit" type="hidden" value="" />
    <svg
      aria-hidden="true"
      class="MuiSvgIcon-root MuiSelect-icon MuiSelect-iconOutlined"
      focusable="false"
      role="presentation"
      viewBox="0 0 24 24"
    >
      <path d="M7 10l5 5 5-5z" />
    </svg>
    <fieldset
      aria-hidden="true"
      class="PrivateNotchedOutline-root-242 MuiOutlinedInput-notchedOutline"
      style="padding-left: 8px;"
    >
      <legend
        class="PrivateNotchedOutline-legend-243"
        style="width: 0.01px;"
      >
        <span>?</span>
      </legend>
    </fieldset>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我在同一个表单上有另一个字段,它根据此选择字段的值呈现。

我想测试这样的东西:

const selectField = screen.getByTestId('fruit');
fireEvent.change(selectField, {
    target: { value: 'APPLE' }
});
expect(selectField.value).toBe('APPLE');
expect(anotherField).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)

它在第二次期望中失败。测试此类表单的正确方法是什么?

小智 9

你应该将data-testid道具传递给inputProps类似的人

<TextField
  select
  id="fruit"
  inputProps={{ id: "fruit", 'data-testid': "fruit" }}
  fullWidth
  variant="outlined"
  {...errors}
>
Run Code Online (Sandbox Code Playgroud)

然后你可以做

const fruit = getByTestId('fruit');
fireEvent.change(fruit, { target: { value: 'APPLE' } });
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,但感觉它并没有真正测试 UI 是否工作,而是可以通过编程方式设置该值。 (6认同)