如何使用KARMA对React JSX ES6代码进行单元测试?

时间:2015-04-03 18:49:52

标签: javascript reactjs karma-runner react-jsx babeljs

我用ES6编写了我的React应用程序。现在我想用ES6编写我的测试。所以这里的挑战是配置业力。

与谷歌一起,我带着karma.config.js走了这一步(我省略了配置文件的相同部分!):

...
files: [
  '../node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
  '../app/**/*.jsx',
  '../test/**/*.jsx'],

 preprocessors: {
  'app/**/*.jsx': ['react-jsx', 'babel'],
  'test/**/*.jsx': ['react-jsx', 'babel']
 },
 'babelPreprocessor': {
  options: {
    sourceMap: 'inline'
  },
  filename: function(file) {
    return file.originalPath.replace(/\.jsx$/, '.es5.js');
  },
  sourceFileName: function(file) {
    return file.originalPath;
  }
},
....

我认为这个设置应该做什么:1)将JSX编译为JS,然后babel将ES6转换为ES5。这与我预期的polyfill一起应该在phantomjs中运行。但不,这是我运行时的业力输出:

PhantomJS 1.9.8 (Mac OS X) ERROR
    SyntaxError: Parse error
    at Projects/ES6/app/js/app.jsx:35
    PhantomJS 1.9.8 (Mac OS X): Executed 0 of 0 ERROR (0.027 secs / 0 secs)
    [20:36:59] Karma has exited with 1

app.jsx的第35行包含实际的JSX部分。因此,出于某种原因,预处理器似乎并没有那么多。任何有关预处理器的帮助都会受到赞赏吗?

更新:我有这个几乎工作的nog。事实证明我应该像这样交换预处理器

 '../app/**/*.jsx': ['babel', 'react'], 
 '../test/**/*.jsx': ['babel', 'react']

现在,当我运行时,我得到:

Uncaught ReferenceError: require is not defined

我以为我有一个polyfill :(

2 个答案:

答案 0 :(得分:5)

我在浏览器和JSX中使用ES6。对于编译我使用Babel。以下配置适用于我。

<强> karma.conf.js

...
frameworks: ['browserify', 'jasmine'],
files: [
  'Component.js',                     // replace with your component
  '__tests__/Component-test.js'
],
preprocessors: {
  'Component.js': 'browserify',
  './__tests__/Component-test.js': 'browserify'
},
browserify : {
  transform : ['babelify']
},
...

<强> __测试__ /组件的test.js

var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var Component = require('../Component.js');

describe('Component', () => {

  it('should work', () => {
    var component = <Component />;
    TestUtils.renderIntoDocument(component);
    expect(component).toBeTruthy();
  });

});

如果您有任何问题,请告诉我。

答案 1 :(得分:4)

@zemirico回答对我不起作用,有点过时了。

以下是我自己可以用于karma.conf.js的设置:

...
frameworks: ['jasmine', 'browserify'],

files: [
    'src/*',
    'tests/*'
],

preprocessors: {
    'src/*': ['browserify'],
    'tests/*': ['browserify']
},

browserify: {
    debug: true,
    transform: ['babelify']
}
...

它使用babelify代替reactify,并具有其他依赖项。因此,还需要项目根目录中的.babelrc

{
  presets: ['es2015', 'react']
}

设置还要求下面的依赖项包含在package.json文件中:

  "devDependencies": {
    "babel-preset-react": "^6.5.0",
    "babelify": "^7.2.0",
    "browserify": "^13.0.0",
    "jasmine-core": "^2.4.1",
    "karma": "^0.13.22",
    "karma-browserify": "^5.0.3",
    "karma-chrome-launcher": "^0.2.3",
    "karma-jasmine": "^0.3.8",
    "watchify": "^3.7.0",
    "babel-preset-es2015": "^6.6.0",
    "react": "^15.0.1",
    "react-addons-test-utils": "^15.0.1",
    "react-dom": "^15.0.1"
  }

用法

src/my-element.jsx中创建一个新的React组件:

import React from 'react';

export default class MyElement extends React.Component {

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

    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.setState({isActive: !this.state.isActive});
  }

  render() {
    return (
      <div onClick={this.onClick}>{this.state.isActive ? "I am active!" : "I am not active :("}</div>
    );
  }
}

然后,通过在tests/my-element-spec.js中创建规范来测试它:

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import MyElement from '../src/my-element.jsx';

describe('MyElement', () => {

  // Render a checkbox with label in the document
  const element = TestUtils.renderIntoDocument(<MyElement />);
  const elementNode = ReactDOM.findDOMNode(element);

  it('verity correct default text', () => {
    expect(elementNode.textContent).toEqual('I am not active :(');
  });

  it ('verify text has been changed successfuly after click', () => {
    // Simulate a click and verify that it is now On
    TestUtils.Simulate.click(elementNode);

    // Verify text has been changed successfully
    expect(elementNode.textContent).toEqual('I am active!');
  });
});

演示

Working example on GitHub