My Text Input is:
<TextField
className={classes.textField}
data-testid={name}
variant="outlined"
error={false}
required
onChange={(element) => {
if (onTextChange) {
onTextChange(name, element.target.value);
}
}}
disabled={!editEnable}
name={name}
label={label}
defaultValue={values}
fullWidth
/>;
and UI:
How to change the value of this text element in the React testing library?
In my case it works like this
it('should render input ', () => {
const field = screen.getByTestId('search-text-field').querySelector('input')
expect(field ).toBeInTheDocument()
fireEvent.change(field , {target: { value: 'google it'}});
expect(field.value).toBe('google it');
});
I don't think getting the input by the display value is a good idea as if that changes the whole test will fail. Instead you should get the label of the input field.
screen.getByLabelText(/^label/i)
Update
Just realised that my way only works if you include an id to the TextField and the ID must match the name. This does seem to be the preferred way to get the input via Material UI as you don't need to include a test-id or by the value.
<TextField
name={name}
id={name}
label={label}
{...otherProps}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With