如何在React Testing Library中获取Material-UI密码输入框

4

我在一个项目中使用Material-UI和React Testing Library,但在设置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 的情况下获得该密码框呢?
1个回答

10

我认为你需要将id属性设置为TextField,这样它才能将标签与输入框关联起来。


这个会是什么样子?我尝试将它传递给SelectPropsMenuProps,但没有成功。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接