React テスト ライブラリ: 入力フォームで fireEvent が変更されたときに、指定された要素に値セッターがありません 質問する

React テスト ライブラリ: 入力フォームで fireEvent が変更されたときに、指定された要素に値セッターがありません 質問する

値を変更したいマテリアルUI TextFieldReact テスト ライブラリで、すでに 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: '[email protected]' } })

しかし、これはエラーを返すため機能しません: The given element does not have a value setter。要素はe.target.valueそのonChange属性を使用していませんか? 何が間違っているのでしょうか?

ベストアンサー1

ここでの問題はテキストフィールドは、MaterialUI の抽象化です。FormControl、Label、Input で構成されます。この問題をクリーンに解決する方法は次のとおりです。

  • まず、属性InputProps付きの TextField を追加しますdata-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

おすすめ記事