使用mocha和jsdom失败的反应单元测试

时间:2016-06-21 16:46:50

标签: javascript unit-testing reactjs

我正在使用mocha和jsdom对React进行基本单元测试。

这是我的代码:

var React = require('react/addons'),
    assert = require('assert'),
    TodoItem = require('../app/components/todo-item.jsx'),
    TestUtils = React.addons.TestUtils;

describe('Todo-item component', function(){
  before('render and locate element', function() {
    var renderedComponent = TestUtils.renderIntoDocument(
      <TodoItem done={false} name="Write Tutorial"/>
    );

    // Searching for <input> tag within rendered React component
    // Throws an exception if not found
    var inputComponent = TestUtils.findRenderedDOMComponentWithTag(
      renderedComponent,
      'input'
    );

    this.inputElement = inputComponent.getDOMNode();
  });

  it('<input> should be of type "checkbox"', function() {
    assert(this.inputElement.getAttribute('type') === 'checkbox');
  });

  it('<input> should not be checked', function() {
    assert(this.inputElement.checked === false);
  });

});

TodoItem的React代码是:

var React = require('react');

module.exports = React.createClass({
  displayName: 'TodoItem',

  getInitialState: function() {
    return { done: this.props.done }
  },

  render: function() {
    return (
      <label>
        <input type="checkbox" defaultChecked={this.state.done} />
        {this.props.name}
      </label>
    );
  }
});

我收到错误说明未定义的令牌:

Unexpected token (10:6)
   8 |   before('render and locate element', function() {
   9 |     var renderedComponent = TestUtils.renderIntoDocument(
> 10 |       <TodoItem done={false} name="Write Tutorial"/>
     |       ^
  11 |     );
  12 | 
  13 |     // Searching for <input> tag within rendered React component

我使用的gulpfile如下:

gulp.task('test', function() {
  gulp.src('./tst/**/*.js')
  .pipe(mocha({
    reporter: 'spec',
    compilers: {
      js: require('babel-core/register')
    }
  }));
});

我做错了什么。我正在尝试按照教程。

1 个答案:

答案 0 :(得分:0)

我刚从链接教程中的package.json中复制了这个。尝试运行你的测试:

mocha test/**/*-test.js --compilers js:babel-core/register --recursive