测试React组件Jasmine和Webpack时出现语法错误

时间:2016-01-15 21:30:57

标签: testing reactjs jasmine karma-runner webpack

我在尝试使用React,Karma,Jasmine和Webpack运行简单测试时遇到错误。错误是'未捕获的SyntaxError:意外的令牌< ',我认为我的jsx没有被处理成js,但我不知道为什么会发生这种情况,因为我理解webpack应该使用babel加载器处理它。如果有人可以提供建议,我将不胜感激

这是我的文件

karma.conf.js

var webpack = require("webpack"),
  path = require("path");

// Karma configuration

module.exports = function(config) {
  config.set({
    basePath: "",
    frameworks: ["jasmine"],
    files: [
      "../test/!**!/!*.test.js"
    ],
    preprocessors: {
      "./test/!**!/!*.test.js": ["webpack"]
    },
    webpack: {
      module: {
          loaders: [
      {
        test: /\.jsx?$/i,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-1']
        }
      },
      { test: /\.less$/, loader: "style!css!less" }
    ]
  },
      },
      plugins: [
        new webpack.ResolverPlugin([
          new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        ])
      ],
      resolve: {
        root: __dirname,
        extensions: [
          '',
          '.json',
          '.js',
          '.jsx'
        ]
      }
    },
    webpackMiddleware: {
      noInfo: true
    },
    plugins: [
      require("karma-webpack"),
      require("karma-jasmine"),
      require("karma-chrome-launcher")
    ],
    reporters: ["dots"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ["Chrome"],
    singleRun: false
  });
};

我的测试文件example.test.js

var Comp = require('../../../js/common/components/MyComp.jsx'),
  React = require('react'),
  TestUtils = React.addons.TestUtils;

describe("Component Test", function() {
  it("renders an h1", function () {
    var component = TestUtils.renderIntoDocument(
      <Comp/> // syntax error here
    );

    var h2 = TestUtils.findRenderedDOMComponentWithTag(
      component, 'h2'
    );

    expect(h1).toExist();
  });
});

因此语法错误发生在&lt; Comp ...谢谢!

1 个答案:

答案 0 :(得分:0)

道歉,在设置测试文件的正确路径时出错。

files: [
  "../test/**/*.test.js"
],
preprocessors: {
  "../test/**/*.test.js": ["webpack"]
},