RoadMovie

write down memos or something I found about tech things

React.js & redux-form のテストをmocha & chai で書く

reactjs, redux-form, mocha, chai


こんにちは。この記事ではredux-formをReact.jsで使った際のテストについて紹介したいと思います。 話をシンプルにするために、簡単なcomponentとreducerのテストを見せます。

下記がテスト用に使っているライブラリになります。

※コードはES6で書いてwebpack等でコンパイルすることを前提にしてます。

test
├── components
│   └── postcode.spec.js
├── reducers
│   └── index.spec.js
└── setup.js

Component test

ここでテストしているのは

  • componentが正しいタイトルを持っているか
  • componentが正しいfieldを持っているか
  • componentが正しい値を返すか

になります。 redux-formではそれぞれのcomponentにstoreを渡す必要があります。なので、ここではcomponentをProviderでラップしています。また、onSubmitのメソッドとして returnState を渡しているので、送信ボタンを押したあとの値をそこでチェックすることができます。

Reducers test

Tips for jsdom

もしチュートリアル通りにやっていれば、 mocha-jsdom: already a browser environment or mocha-jsdom invoked twice. use 'skipWindowCheck' というエラーをみたことがあるかもしれません。これを避けるために setup.js を用意しました。windowdocument を遣う場所でこれをロードしておけばこのエラーを避けることができます。

Test command

最後に、テストは下記のコマンドで実行することができます。

$ npm run test

in package.json

scripts: {
    test: mocha --compilers js:babel-core/register --colors ./test/**/*.spec.js
}

References

mocha-jsdom (to avoid mocha-jsdom: already a browser environment or mocha-jsdom invoked twice. use 'skipWindowCheck') https://github.com/rstacruz/mocha-jsdom/blob/master/examples/basic/test.js

redux-form integration test https://github.com/tylercollier/redux-form-test/blob/master/tests/integration/index.js

unit test https://github.com/tylercollier/redux-form-test/blob/master/tests/unit/index.js#L76

basic test syntax for redux http://redux.js.org/docs/recipes/WritingTests.html

syntax for chai http://chaijs.com/api/bdd/


それでは!