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 input element.
// the component <TextField data-testid="input-email" variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" name="email" value={email} onChange={e => setEmail(e.target.value)} autoComplete="email" autoFocus /> // the test //... let userInput = getByTestId('input-email') fireEvent.change(userInput, { target: { value: '[email protected]' } })
but this doesn't work as it's returning error: The given element does not have a value setter
. Isn't the element uses e.target.value
on it's onChange
attribute? What am I do wrong?
Using fireEvent. change() on a select element fires the event handler, but doesn't update state.
fireEvent ( async )It is an async method due to calling tick which tells Svelte to flush all pending state changes, basically it updates the DOM to reflect the new changes.
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
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