Karma不适用于ES6

时间:2016-09-17 00:51:12

标签: javascript webpack karma-jasmine

我想使用karma作为我的js测试环境,但未能将其配置为与ES6一起使用。

以下是我的测试js文件:

import { shallow } from 'enzyme';
import React from 'react';

describe('<MyComponent />', () => {

  it('should render three <Foo /> components', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.find(Foo)).to.have.length(3);
  });
});

当运行karma start时,我会收到此错误:

未捕获的SyntaxError:意外的令牌导入   at test / features / consulting / question / question.js:1

似乎业力不能与babel一起编译ES6。我的配置出了什么问题?

以下是我的karma.conf.js:

var path = require('path');

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'test/**/*.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    webpack: { //kind of a copy of your webpack config
      devtool: 'inline-source-map', //just do inline source maps instead of the default
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel-loader?presets=es2015',
            exclude: path.resolve(__dirname, 'node_modules'),
            include: [
              path.join(__dirname, 'app'),
              path.join(__dirname, 'test')
            ],
          },
          {
            test: /\.json$/,
            loader: 'json',
          },
        ]
      },
      externals: {
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
      }
    },

    webpackServer: {
      noInfo: true //please don't spam the console when running in karma!
    },
  })
}

我的.babelrc文件如下:

{


"presets": [
    "es2015",
    "react",
    "stage-2"
  ]

}

EDIT1 下面是我的webpack配置文件。由于webpack配置是在karma配置文件上设置的,我是否需要在webpack配置文件上进行任何配置?

const webpack = require('webpack');
const path = require('path');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
var CompressionPlugin = require("compression-webpack-plugin");

const PATHS = {
  react: path.join(__dirname, 'node_modules', 'react', 'dist', 'react.min.js'),
  app: path.join(__dirname, 'src'),
  build: path.join(__dirname, './dist')
};

module.exports = {
  entry: {
    app: './app/index.jsx',
    android: './app/utils/platform_android.js',
    ios: './app/utils/platform_ios.js',
    web: './app/utils/platform_web.js',
    wx: './app/utils/platform_wx.js',
    vendor: [
      'axios',
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux',
      'redux-thunk',
      'react-alert',
      'sha1',
      'moment',
      'nuka-carousel',
      'react-cookie',
      'react-spinkit',
      'react-tap-event-plugin',
      'react-tappable',
      'history',
      "react-pull-to-refresh",
      "react-infinite-scroller",
      'pingpp-js',
    ],
  },
  output: {
    path: PATHS.build,
    filename: '[name].bundle.js',
  },
  watch: false,
  devtool: 'source-map',
  relativeUrls: true,
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.less'],
    modulesDirectories: ['node_modules'],
    alias: {
      normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',
    }
  },
  module: {
    preLoaders: [

      {
        test: /\.js$/,
        loader: "source-map-loader"
      },
    ],
    loaders: [

      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]',
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader?presets=es2015',
      },
      {
        test: /\.less$/,
        loader: "style!css!less",
      },
      {test: /\.css$/, loader: 'style-loader!css-loader'},
      {test: /\.png$/, loader: "url-loader?limit=100000"},
      // {test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[path]/[name].[ext]"},
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ['babel-loader?presets=es2015']
      },
      {
        test: /\.svg$/,
        loader: 'svg-sprite',
        include: /public\/icons/
      }
    ]
  },
  plugins: [
    new NpmInstallPlugin({
      save: true // --save
    }),
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("development")
      }
    }),
    new WebpackShellPlugin({
      onBuildStart: [''],
      onBuildEnd: [
        'cp ./dist/*.js ../assets/dist/;rm -fr dist/web;' +
        'mkdir -p dist/web/dist;cp ./dist/*.js ./dist/web/dist/;cp ./index.html ./dist/web/;cp -r public dist/web/',
      ]
    }),
    new CompressionPlugin(),
    new webpack.optimize.CommonsChunkPlugin(/* chunkName= */["vendor"], /* filename= */"[name].bundle.js", Infinity),
  ],
  devServer: {
    colors: true,
    contentBase: __dirname,
    historyApiFallback: true,
    hot: true,
    inline: true,
    port: 9093,
    progress: true,
    stats: {
      cached: false
    }
  }
}

1 个答案:

答案 0 :(得分:1)

经过一番尝试,我弄明白了。 首先,我需要在karma配置文件中添加以下设置。

query: {
      presets: ['airbnb']
}

然后安装这些依赖项:

 babel-preset-airbnb karma-babel-preprocessor

之后,业力能够与es6一起使用。

以下是我的完整业力配置文件:

// Karma configuration
// Generated on Fri Sep 16 2016 23:00:18 GMT+0800 (CST)
var path = require('path');

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'test/**/*.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'app/**/*.jsx': ['webpack', 'sourcemap'],
      'app/**/*.js': ['webpack', 'sourcemap'],
      'test/**/*.js': ['webpack', 'sourcemap']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    webpack: { //kind of a copy of your webpack config
      devtool: 'inline-source-map', //just do inline source maps instead of the default
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: path.resolve(__dirname, 'node_modules'),
            include: [
              path.join(__dirname, 'app'),
              path.join(__dirname, 'test')
            ],
            query: {
                           presets: ['airbnb']
             }
          },
          {
            test: /\.json$/,
            loader: 'json',
          },
        ]
      },
      externals: {
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
      }
    },

    webpackServer: {
      noInfo: true //please don't spam the console when running in karma!
    },

    plugins: [
      'karma-webpack',
      'karma-jasmine',
      'karma-sourcemap-loader',
      'karma-chrome-launcher',
      'karma-phantomjs-launcher'
    ],

    babelPreprocessor: {
      options: {
        presets: ['airbnb']
      }
    },

  })
}