React 测试库:当输入表单上的 fireEvent 发生变化时,给定元素没有值设置器

新手上路,请多包涵

我想在反应测试库中更改 材质 UI TextField 的值。我已经设置了 data-testid。然后使用 getByTestId 我拿起了输入元素。

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

但这不起作用,因为它返回错误: The given element does not have a value setter 。元素不是在它的 onChange 属性上使用 e.target.value --- 吗?我做错了什么?

原文由 otong 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 498
1 个回答

这里的问题是 TextField 是 MaterialUI 中的抽象。它由 FormControl、Label 和 Input 组成。解决这个问题的干净方法是:

  • 首先,在您的 TextField 上添加 InputPropsdata-testid 属性。
 // YourComponent.js

<TextField
  onChange={event => setContent(event.target.value)}
  id="content"
  inputProps={{ "data-testid": "content-input" }}
  value={content}
  label="Content"
/>

  • 然后只需使用此 ID 进行查询。
 // YourComponent.test.js

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

// and then assert stuff in here

原文由 Franek Madej 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题