I have an MUI form that I want to test. All the form fields are required and I want to test that using @testing-library/react
Here's the form:
<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>
And here's how I'm testing it:
test('All fields are required', () => {
render(<XMLForm />);
expect(
getByTestId(document.documentElement, 'required-firstName')
).toBeRequired();
expect(
getByTestId(document.documentElement, 'required-lastName')
).toBeRequired();
});
The test fails at the first form field. Regardless of if I use <TextField /> or <FormControl />, the rendered DOM elements don't seem to have the required field and I have no idea why.
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();
requiredattribute on<div class="MuiInputBase-root ..." />which doesn't make sense instead of an real<input />. But not sure why have you done that?