如何在 React 测试库中获取 Material-UI 密码输入

How to get a Material-UI password input in React Testing Library

我在一个项目中使用 Material-UI 和 React 测试库,我很难使用设置为 type="password" 的 TextField。我知道,在测试中,默认使用 testId 字段获取元素不是一个好习惯,但我找不到进入密码输入字段的方法。我不能使用 getByRole 因为显然 <input type="password"> 没有作用。输入框中没有文本,也没有占位符文本,当我尝试使用 getByLabelText 时,我收到此错误消息:

TestingLibraryElementError: Found a label with the text of: Password, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly.

当我查看测试中呈现的元素时(我使用 screen.debug()),我意识到这就是 Material-UI 组成 TextField 的方式:

<div>
  <div
      class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth"
    >
    <label
      class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated"
      data-shrink="false"
    >
      Password
    </label>
    <div
      class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl"
    >
      <input
        aria-invalid="false"
        class="MuiInputBase-input MuiInput-input"
        name="pass"
        type="password"
        value=""
      />
    </div>
  </div>
</div>

因此,<input> 未嵌入到 <label> 中,而且标签也没有 for 属性将其与输入相关联。那么,如果不使用 testId,我还能如何获得该密码框?

我认为您需要将 id 属性设置为 TextField 才能将标签关联到输入