gpt4 book ai didi

reactjs - Material-UI 表单和 React 测试库所需的表单字段

转载 作者:行者123 更新时间:2023-12-04 08:10:42 30 4
gpt4 key购买 nike

我有一个要测试的 MUI 表单。所有表单字段都是必需的,我想使用 @testing-library/react 测试它
这是表格:

<form id='xml-form' onSubmit={handleSubmit}>
<div
<FormControl required={true}>
<InputLabel required={true}>Name</InputLabel>
<Input
id='firstName'
data-testid='required-firstName'
required={true}
/>
</FormControl>
</div>
<div>
<TextField
id='lastName'
data-testid='required-lastName'
required
label='Last Name'
style={{ marginBottom: 15 }}
/>
</div>
<Button
type='submit'
form='xml-form'
color='primary'
variant='contained'
style={{ marginBottom: 15 }}
>
Generate XML
</Button>
</form>
这是我测试它的方式:
test('All fields are required', () => {
render(<XMLForm />);
expect(
getByTestId(document.documentElement, 'required-firstName')
).toBeRequired();
expect(
getByTestId(document.documentElement, 'required-lastName')
).toBeRequired();
});
测试在第一个表单域失败。无论我是否使用 <TextField /><FormControl /> ,渲染的 DOM 元素似乎没有必填字段,我不知道为什么。
Received element is not required:
<div class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-formControl MuiInput-formControl" data-testid="required-firstName" required="" />

7 | expect(
8 | getByTestId(document.documentElement, 'required-firstName')
> 9 | ).toBeRequired();
| ^
10 | expect(
11 | getByTestId(document.documentElement, 'required-lastName')
12 | ).toBeRequired();

最佳答案

您需要通过data-testidinputProps使用时 <Input /> <TextField /> :

<form id='xml-form' onSubmit={handleSubmit}>
<div
<FormControl required={true}>
<InputLabel required={true}>Name</InputLabel>
<Input
id='firstName'
inputProps={{ 'data-testid': 'required-firstName' }}
required={true}
/>
</FormControl>
</div>
<div>
<TextField
id='lastName'
inputProps={{ 'data-testid': 'required-lastName' }}
required
label='Last Name'
style={{ marginBottom: 15 }}
/>
</div>
<Button
type='submit'
form='xml-form'
color='primary'
variant='contained'
style={{ marginBottom: 15 }}
>
Generate XML
</Button>
</form>
或者,我相信您可以使用 getByLabelText() 询问。对于您感兴趣的两个元素,它将是:
test('All fields are required', () => {
render(<XMLForm />);
expect(
getByLabelText(document.documentElement, 'Name')
).toBeRequired();
expect(
getByLabelText(document.documentElement, 'Last Name')
).toBeRequired();
});

关于reactjs - Material-UI 表单和 React 测试库所需的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65981875/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com