【问题标题】:How to test Material UI Select Component with React Testing Library如何使用 React 测试库测试 Material UI 选择组件
【发布时间】:2020-04-26 23:05:37
【问题描述】:

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

以下是我的选择组件。

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>

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>

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

我想测试这样的东西:

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

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

【问题讨论】:

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


【解决方案1】:

您应该将data-testid 属性传递给inputProps 喜欢

<TextField
  select
  id="fruit"
  inputProps={{ id: "fruit", 'data-testid': "fruit" }}
  fullWidth
  variant="outlined"
  {...errors}
>

然后你就可以了

const fruit = getByTestId('fruit');
fireEvent.change(fruit, { target: { value: 'APPLE' } });

【讨论】:

  • 是的,这也是我目前发现的最好方法,因为在这种情况下,Material UI 是基本组件选择的包装器,您必须通过 inputProps 指定 data-testId。
  • 这对我有用,但感觉它并没有真正测试 UI 是否有效,而是可以通过编程方式设置值。
猜你喜欢
  • 1970-01-01
  • 2020-05-03
  • 2023-03-13
  • 2022-06-29
  • 2018-11-27
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多