Skip to content Skip to sidebar Skip to footer

React Testing Library: The Given Element Does Not Have A Value Setter When FireEvent Change On Input Form

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 compone

Solution 1:

Problem here is TextField is an abstraction in MaterialUI. It consists of FormControl, Label and Input. Clean way of solving this problem is:

  • First, add 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"
/>
  • Then simply query using this ID.
// YourComponent.test.js

const contentInput = getByTestId("content-input");
fireEvent.change(contentInput, {
  target: { value: "new content" }
});

// and then assert stuff in here

Solution 2:

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' } });

Solution 3:

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.


Solution 4:

I tested the answers and comments and the only solutions that works for me was userEvent.

First install the dependency npm install --save-dev @testing-library/user-event

Then in your test file calls:

import { render, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
    
    ...
it('Awesome input test', async () => {
await act(async () => {
    const inputMessage = getByTestId('input-send-message');
    userEvent.type(inputMessage, 'My awesome text...');
  })
})
//expect goes here

More here


Solution 5:

In my case I had InputProps two times because I had an endAdornment. Just make sure that you put your data-testid attribute where it belongs. Example:

<TextField
InputProps={
  {
    inputProps: {
      min: 0,
      'data-testid': 'value'
    },
    endAdornment: < InputAdornment position = "end" > % < /InputAdornment>,
  }
}
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Post a Comment for "React Testing Library: The Given Element Does Not Have A Value Setter When FireEvent Change On Input Form"