I want to change the value of material UI TextField
in react testing library.
I already set up the data-testid. Then using getByTestId
i picked up the
the issue here is when we use Material UI, it renders the TextField component having one of the elements inside it as an input field. And only "input" has getter and setter on it. So after you got the TextField, you have to get the "input" element of your TextField using querySelector() of your DOM object.
const field = getByTestId('input-email').querySelector('input');
// now fire your event
fireEvent.change(field, { target: { value: 'abcd@xyz.com' } });
You can use fireEvent.change
on an element that supports that event like <input>
. In your case, I'm not sure what you're selecting. You can try to debug(userInput)
to see what it returns.
Problem here is TextField is an abstraction in MaterialUI. It consists of FormControl, Label and Input. Clean way of solving this problem is:
InputProps
on your TextField, with data-testid
attribute.// YourComponent.js
<TextField
onChange={event => setContent(event.target.value)}
id="content"
inputProps={{ "data-testid": "content-input" }}
value={content}
label="Content"
/>
// YourComponent.test.js
const contentInput = getByTestId("content-input");
fireEvent.change(contentInput, {
target: { value: "new content" }
});
// and then assert stuff in here