简体   繁体   中英

Karma doesn't work with ES6

I want to use karma as my js test environment but failed to configure it to work with ES6.

Below is my test js file:

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);
  });
});

When run karma start, I will get this error:

Uncaught SyntaxError: Unexpected token import at test/features/consulting/question/question.js:1

It seems that karma doesn't work with babel to compile ES6. What's wrong with my configuration?

Below is my 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!
    },
  })
}

and I have .babelrc file as below:

{


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

}

EDIT1 Below is my webpack config file. Since the webpack configuration is set on karma config file, do I need any configuration on webpack conf file?

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
    }
  }
}

After some try I figured it out. First I need to add below settings on karma config file.

query: {
      presets: ['airbnb']
}

then install these dependencies:

 babel-preset-airbnb karma-babel-preprocessor

After that, karma is able to work with es6.

Below is my complete karma config file:

// 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']
      }
    },

  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM