单元测试反应JSX ES6

时间:2016-03-12 10:48:17

标签: javascript unit-testing reactjs ecmascript-6 karma-runner

我正在使用 React JSX ES6 Karma

有人知道我的代码有什么问题吗?

我正试图通过Karma-Runner传递此测试但是出了点问题:

let React = require("react");
let TestUtils = React.addons.TestUtils;
let expect = require("expect");

/* global describe */
/* global it */
describe("Header", function () {
  it("renders without problems", function () {
    let component = <Header/>;
    let header = TestUtils.renderIntoDocument(component);

    expect(header).toExist();
  });
});

$ karma start命令之后,这是错误:

Module build failed: SyntaxError: /Users/aralroca/react-es6-boilerplate/app/tests/components/header.test.js: Unexpected token (9:20)
   7 | describe("Header", function () {
   8 |   it("renders without problems", function () {
>  9 |     let component = <Header/>;
     |                     ^
  10 |     let header = TestUtils.renderIntoDocument(component);
  11 | 
  12 |     expect(header).toExist();

非常感谢你。

被修改

karma.conf.js

module.exports = function (config) {
  config.set({
    browsers: [ process.env.CONTINUOUS_INTEGRATION ? "Firefox" : "Chrome" ],
    files: [
      "tests.bundle.js"
    ],
    frameworks: ["chai", "mocha"],
    plugins: [
      "karma-chrome-launcher",
      "karma-chai",
      "karma-mocha",
      "karma-sourcemap-loader",
      "karma-webpack"
    ],
    preprocessors: {
      "tests.bundle.js": ["webpack", "sourcemap"]
    },
    reporters: ["dots"],
    singleRun: true,
    webpack: {
      devtool: "inline-source-map",
      module: {
        loaders: [
          {
            exclude: /node_modules/,
            loader: "babel-loader",
            test: /\.jsx?$/
          }
        ]
      }
    },
    webpackMiddleware: {
      noInfo: true
    }
  });
};

1 个答案:

答案 0 :(得分:0)

如果你想在测试中使用JSX,你需要连接karma-babel-preprocessor

这会让babel在执行前运行测试。否则,当karma运行测试时,ES6或JSX语法将导致错误。