React testing library: The given element does not have a value setter when fireEvent change on input form

独自空忆成欢 提交于 2020-02-21 12:35:11

问题


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: 'correct@mail.com' } })

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?


回答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



回答2:


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.



来源:https://stackoverflow.com/questions/57110557/react-testing-library-the-given-element-does-not-have-a-value-setter-when-firee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!