【发布时间】:2021-02-12 12:38:21
【问题描述】:
我在一个项目中使用 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,我还能如何获得那个密码框呢?
【问题讨论】:
标签: reactjs material-ui react-testing-library