LoginSignup
13
5

More than 5 years have passed since last update.

Enzymeでテキスト変更をsimulateする

Posted at

Reactでユニットテストを書くときには、ユーティリティとしてairbnbのenzymeを使うと便利。

enzymeはshallowやmountといったI/Fでレンダリングを模擬してくれる。
またsimulateメソッドを利用してDOMのイベントを模擬できる。

ボタンクリック

クリックはドキュメントにもあるが、以下のように記述できる。

const wrapper = mount(<a onClick={() => alert('click!!')}/>);
wrapper.find('a').simulate('click');
// click!!

テキストフィールド変更

テキストフィールド(input type=text)の場合は、対象nodeのvalueを変更してからchangeを模擬する。

const wrapper = mount(<Foo />);
wrapper.find('input').get(0).value = 'My new value';
wrapper.find('input').first().simulate('change');

よりシンプルにやる方法も紹介されている。
simulateの第2引数のモックイベントオブジェクトを利用する。

const wrapper = mount(<Foo />);
wrapper.find('input').simulate('change', {target: {value: 'My new value'}});

参考

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5