javascript jest

Jestのサンプル。 単にtutorialをやっただけ。

├── .babelrc
├── __tests__
│   └── CheckboxWithLabel-test.js
├── package.json
└── src
    └── CheckboxWithLabel.js
(Φ ω Φ >        cat .babelrc
{
  "presets": ["es2015", "react"]
}
Φ ω Φ > cat package.json
{
  "name": "jest-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "react": "~15.0.0",
    "react-dom": "~15.0.0"
  },
  "devDependencies": {
    "babel-jest": "^9.0.0",
    "babel-preset-es2015": "*",
    "babel-preset-react": "*",
    "jest-cli": "*",
    "react-addons-test-utils": "~15.0.0"
  },
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react/",
      "<rootDir>/node_modules/react-dom/",
      "<rootDir>/node_modules/react-addons-test-utils/"
    ]
  },
  "author": "",
  "license": "ISC"
}
(Φ ω Φ > cat src/CheckboxWithLabel.js
import React from 'react';

export default class CheckboxWithLabel extends React.Component {

  constructor(props) {
    super(props);
    this.state = {isChecked: false};

    // bind manually because React class components don't auto-bind
    // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
    this.onChange = this.onChange.bind(this);
  }

  onChange() {
    this.setState({isChecked: !this.state.isChecked});
  }

  render() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.onChange}
        />
        {this.state.isChecked ? this.props.labelOn : this.props.labelOff}
      </label>
    );
  }
}
(Φ ω Φ > cat __tests__/CheckboxWithLabel-test.js
jest.unmock('../src/CheckboxWithLabel');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import CheckboxWithLabel from '../src/CheckboxWithLabel';

describe('CheckboxWithLabel', () => {
  it('changes the text after click', () => {
    const checkbox = TestUtils.renderIntoDocument(
      <CheckboxWithLabel labelOn="On" labelOff="Off" />
    );
    const checkboxNode = ReactDOM.findDOMNode(checkbox);

    expect(checkboxNode.textContent).toEqual('Off');

    TestUtils.Simulate.change(
      TestUtils.findRenderedDOMComponentWithTag(checkbox, 'input')
    );
    expect(checkboxNode.textContent).toEqual('On');
  });
});