Testing React.js & redux-form with mocha and chai

2017-04-04 18:10
2017-04-04 18:10

reactjs, redux-form, mocha, chai

Guten Tag!

In this article, I want to introduce the way to test React.js components with redux-form.
To make it simple, I just show a simple component test and reducer test. It's not complicated. So just let's try!

I'm using some node-modules for test.

On product code, I'm writing in ES6. Then compile files by webpack(w/babel modules).

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

Component test

What I'm testing here is

  • if the component has a correct title
  • if the component has a proper field
  • if the component returns correct values

On redux-form, we need to pass a store for each component. So, here I wrapped the component by Provider. Since I passed the returnState method as onSubmit method, I can check the values after clicking submit button. To do this, don't forget to substitute the result for a variable.

That's it. Not bad :)

Reducers test

Tips for jsdom

If you follow some tutorials, you might encounter an error which says mocha-jsdom: already a browser environment or mocha-jsdom invoked twice. use 'skipWindowCheck'.

To avoid this, I made setup.js. Then I load it by requiring method when I need to use window or document method etc.

Test command

At last, you can run the test by below command.

$ npm run test

in package.json

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


(to avoid mocha-jsdom: already a browser environment or mocha-jsdom invoked twice. use 'skipWindowCheck')

integration test

unit test

basic test syntax for redux

syntax for chai