在使用测试库进行测试时使用 getByRole 时无法获取输入的名称
Unable to get the name of the input when using getByRole while testing with testing-library
我正在测试一个包含 Material Ui TextField 组件的组件(我们称它为 MyComponent):
<TextField
name="code"
aria-label="code"
onKeyPress={keyPressHandler(codeRegExp)}
value={values.code}
placeholder={codePlaceholder}
onChange={handleChange}
InputProps={{
classes: {
input: classes.code,
},
}}
onBlur={handleBlur}
helperText={
touchedValues.code && errorValues.code ? errorValues.code : ''
}
FormHelperTextProps={{classes: {root: classes.errorMessage}}}
/>
我为此编写了测试:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
测试失败,我得到这个错误:
TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/code/i`
Here are the accessible roles:
textbox:
Name "":
<input
aria-invalid="false"
class="MuiInputBase-input MuiInput-input makeStyles-code-9"
name="code"
placeholder="ABC_123"
type="text"
value=""
/>
我应该为 TextField 组件添加 role=textbox
还是 textbox
角色不适用于输入元素?
我正在测试一个包含 Material Ui TextField 组件的组件(我们称它为 MyComponent):
<TextField
name="code"
aria-label="code"
onKeyPress={keyPressHandler(codeRegExp)}
value={values.code}
placeholder={codePlaceholder}
onChange={handleChange}
InputProps={{
classes: {
input: classes.code,
},
}}
onBlur={handleBlur}
helperText={
touchedValues.code && errorValues.code ? errorValues.code : ''
}
FormHelperTextProps={{classes: {root: classes.errorMessage}}}
/>
我为此编写了测试:
test('Checking the initial rendering of the component', () => {
const initialState = {
refs: {
choice: '',
creationDate: '',
},
};
render(<MyComponent />, {initialState});
expect(screen.getByRole('textbox', {name: /code/i})).toBeInTheDocument();
});
测试失败,我得到这个错误:
TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/code/i`
Here are the accessible roles:
textbox:
Name "":
<input
aria-invalid="false"
class="MuiInputBase-input MuiInput-input makeStyles-code-9"
name="code"
placeholder="ABC_123"
type="text"
value=""
/>
我应该为 TextField 组件添加 role=textbox
还是 textbox
角色不适用于输入元素?