Reactjs のテストを karma + karma-fixture + mocha + power-assert で書いてみる



前回書いた [ReactJS + Flumpt のカウンターのサンプル](http://qiita.com/cortyuming/items/54b13904353bd67a3181) にテストを追加してみる。


## karuma インストールと設定

```
$ npm install --save-dev karma
$ node_modules/.bin/karma init
> mocha

> no

> Chrome

>

>
yes
```

### テストで必要なライブラリをインストール

```bash
$ npm install --save-dev babel-plugin-espower karma-browserify power-assert karma-fixture karma-html2js-preprocessor
```

### karma.conf.js

```javascript
// Karma configuration
// Generated on Mon Dec 21 2015 12:22:32 GMT+0900 (JST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'browserify'],


    // list of files / patterns to load in the browser
    files: [
      'test/fixtures/**/*.html',
      'test/**/*.spec.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/fixtures/**/*.html': 'html2js',
      'test/**/*.spec.js': 'browserify'
    },

    browserify: {
      debug: true,
      transform: [
        ['babelify', {plugins: ['babel-plugin-espower']}]
      ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  });
};
```


## テスト用のファイルを書く

```
$ mkdir test
$ emacs test/counter.spec.js
```

### test/counter.spec.js

```javascript
'user strict';

import assert from 'power-assert';


describe('Click a button', () => {
  let countSelector = '.js-container > div > p > span:nth-child(2)';

  before(() => {
    document.body.innerHTML = window.__html__['test/fixtures/index.html'];
    require('../src/app.jsx');
  });

  after(() => {
    document.body.innerHTML = '';
  });

  it('1 increases', () => {
    let incBtn = document.querySelector('button:nth-child(1)');
    let init_count_num = Number(document.querySelector(countSelector).textContent);
    let count_num;

    incBtn.click();

    count_num = Number(document.querySelector(countSelector).textContent);
    assert(init_count_num + 1 === count_num);

  });

  it('1 decreases', () => {
    let decBtn = document.querySelector('button:nth-child(2)');
    let init_count_num = Number(document.querySelector(countSelector).textContent);
    let count_num;

    decBtn.click();

    count_num = Number(document.querySelector(countSelector).textContent);
    assert(init_count_num - 1 === count_num);
  });

});
```

### フィクスチャ

```
$ mkdir test/fixtures/
$ emacs test/fixtures/index.html
```

### test/fixtures/index.html

```html
<div class="js-container"></div>
```


## package.json

`"scripts"` に追加

```json
    "test": "karma start",
```


## テスト 実行

```
$ npm test

Chrome 47.0.2526 (Mac OS X 10.10.5): Executed 2 of 2 SUCCESS (0.103 secs / 0.017 secs)
```


## 参考

- [karma+mocha+power-assertでDOM操作を含むユニットテストをES6で書く](http://webdesign-dackel.com/2015/11/02/karma-mocha-power-assert-dom-test/)
- https://github.com/karma-runner/karma
- https://github.com/billtrik/karma-fixture
- https://github.com/mochajs/mocha
- https://github.com/power-assert-js/power-assert