値を変更したいマテリアルUI TextField
React テスト ライブラリで、すでに 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