如何使用React Testing Library测试材料UI选择组件

问题描述 投票:7回答:1

我正在使用React Testing库进行组件测试。材质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>

[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个回答
0
投票

您应该将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' } });
© www.soinside.com 2019 - 2024. All rights reserved.