TestUtilsが関数コンポーネントダメだって

'use strict';
/*global jest*/
jest.dontMock('../BootstrapResponsive');
const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
import {ResponsiveCol} from '../BootstrapResponsive';
describe('Col', () => {
    it('hidden setting', () => {
        const col = TestUtils.renderIntoDocument(
            <ResponsiveCol xs={{hidden: true}} sm={{hidden: true}} md={{hidden: false}}/>
        );
        const colNode = ReactDOM.findDOMNode(col);
        expect(colNode.getAttribute('class').trim()).toEqual('hidden-xs hidden-sm');
    });
});

Jestで後付けにテスト書いたら、TestUtilsが関数コンポーネント(ステートレスコンポーネント)に対応していなくてダメだって。

Using Jest CLI v0.8.2, jasmine1
Running 1 test suite...Warning: ResponsiveCol(...): No `render` method found on the returned component instance: you may have forgotten to define `render`, returned null/false from a stateless component, or tried to render an element whose type is a function that isn't a React component.

「you may have fogotten to define 'render'」って、忘れてないよ!わざとだよ!「returned null/false from a stateless component」って。。。どう言うこっちゃ?

というところで、これはテストそのものが動かなかったけど、Jestは便利です。以下設定備忘。

babel, babel-preset-es2015, babel-preset-reactはすでに入ってる前提でJestインストール。

$ npm install --save-dev jest-cli babel-jest react-addons-test-utils

package.jsonにJestの設定追加。

{
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react",
      "<rootDir>/node_modules/react-dom",
      "<rootDir>/node_modules/react-addons-test-utils",
      "<rootDir>/node_modules/fbjs"
    ]
  },
  "scripts": {
    "test": "jest"
  }
}

で、あとはソースツリーの書きたいところで、「__tests__」フォルダを作ってその中に.jsファイルを置く。ファイルの中身は冒頭のようなのです。es6もJSXも設定で有効にしてます。中身がJasminなのでJasminな書き方にJest特有のモック自動生成、ReactアドオンTestUtilsのツールで仮想DOM-テストDOMの連携動作が乗っかります。

リファレンスは以下。

リファレンスまとめて気がついた。Jasminは1.3.0で古い。node_modules配下のjest-cliを見ると腹にjasmin2.3.4を抱えてたので切り替える設定がありそう。

追記

。。。切り替え設定ありました。

https://facebook.github.io/jest/docs/api.html#config-testrunner-string

さっきの設定に一行足します。

  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testRunner": "<rootDir>/node_modules/jest-cli/src/testRunners/jasmine/jasmine2.js",
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react",
      "<rootDir>/node_modules/react-dom",
      "<rootDir>/node_modules/react-addons-test-utils",
      "<rootDir>/node_modules/fbjs"
    ]
  },

実行したら、ちゃんと2だって言ってる。今まで1.3でも支障なかったけど今日から2.3にしておこう。

Using Jest CLI v0.8.2, jasmine2
Running 1 test suite...