How to fix the error "ReferenceError: cannot find variable: require" when starting unit test in Karma, Webpack, PhantomJS

I use Karma, Webpack, an enzyme, PhantomJS to test my project response. When I run the command below to run the test cases,

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

I got the error below:

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

In line 3 of the test.js source code, I did not use require , the code is below:

 import { expect } from 'chai'; 

I wander why PhantomJS complains about this error.

The following is the karma config:

 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, }) }; 
+7
webpack karma-jasmine enzyme karma-mocha
source share
1 answer

I think you commented out the presets section of your bootloader. Without es2015 Babel may not know how to handle import statements. ( import is part of ES6 modules, but not yet standard in node.) Have you tried to uncomment the query and presets block?

0
source share

All Articles