如何在Karma,Webpack,PhantomJS中运行单元测试时修复错误'ReferenceError:找不到变量:require'

时间:2016-12-01 10:23:15

标签: webpack karma-jasmine enzyme karma-mocha

我使用Karma,Webpack,酶,PhantomJS来测试我的反应项目。当我在命令下运行以运行测试用例时,

./node_modules/karma/bin/karma start config/karma.conf.js --single-run --browsers PhantomJS

我得到以下错误:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  ReferenceError: Can't find variable: require
  at /dev/test/test.js:3

在test.js的源代码的第3行中,我没有使用require,下面是代码:

import { expect } from 'chai'; 

我想为什么PhantomJS抱怨这个错误。

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

var path = require('path');
var webpackconf = require("./webpack.config")

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['mocha', 'chai'],
    files: [
      '../test/**/*.js'
    ],

    preprocessors: {
      // add webpack as preprocessor
      '../src/**/*.js': ['babel'],
      '../test/**/*.js': ['babel'],
      '../src/**/*.less': ['babel']
    },
    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',
            exclude: /node_modules/,
            // query: {
            //   presets: ['es2015',  'react']
            // }
          },
          {
            test: /\.json$/,
            loader: 'json',
          },{
            test: /\.less$/,
            loader: "style!css!less",
          },
        ]
      },
      externals: {
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true,
        'react/addons': 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',
      'karma-mocha',
      'karma-chai',
      'karma-mocha-reporter',
      'karma-babel-preprocessor'
    ],


    babelPreprocessor: {
      options: {
        presets: ['es2015',  'react'],
        sourceMap: 'inline'
      }
    },
    reporters: ['mocha'],

    // reporter options
    mochaReporter: {
      colors: {
        success: 'blue',
        info: 'bgGreen',
        warning: 'cyan',
        error: 'red'
      },
      symbols: {
        success: '+',
        info: '#',
        warning: '!',
        error: 'x'
      }
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
  })
};

1 个答案:

答案 0 :(得分:2)

我认为您已经注释掉了装载机的presets部分。如果没有es2015预设,babel可能不知道如何处理import语句。 (import是ES6模块的一部分,但在节点中尚未标准化。)您是否尝试取消注释querypresets块?

相关问题