TrongBang
TrongBang

Reputation: 967

Unexpected token 'const' When running webpack, babel and karma

I'm setting up my karma test as shown in https://zirho.github.io/2016/06/06/karma-es6/

Then I have error:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\nSyntaxError: Unexpected token 'const'",
    "str": "An error was thrown in afterAll\nSyntaxError: Unexpected token 'const'"
  }
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 0 of 0 ERPhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 0 of 0 ERROR (0.003 secs / 0 secs)

I googled up and followed the instructions here: SyntaxError: Unexpected token 'const' (with Vue, Karma, Webpack, PhantomJS)

But still no luck.

Following are my files.

I. package.json

"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-lodash": "^3.2.11",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-register": "^6.24.1",
"jasmine-core": "^3.1.0",
"karma": "^2.0.2",
"karma-jasmine": "^1.1.2",
"karma-phantomjs-launcher": "^1.0.4",
"karma-webpack": "^3.0.0",
"phantomjs-prebuilt": "^2.1.16",
"webpack": "^3.4.1",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.6.1"

II. karma.conf.js

My frontend code is under /frontend/.

let karmaInitFile = 'frontend/test/helpers/karma.js';

module.exports = function(config) {
    config.set({
        browsers: ['PhantomJS'],
        files: [
            { pattern: karmaInitFile, watched: false }
        ],
        frameworks: ['jasmine'],
        preprocessors: {
            'frontend/test/**/*.js': ['webpack']
        },
        webpack: {
            module: {
                loaders: [
                    { test: /frontend\/.*\.js$/, 
                        exclude: /node_modules/, 
                        use: {
                            loader: 'babel-loader',
                            options: {
                                presets: ['es2015']
                            }
                        }
                    }
                ]
            },
            watch: true,
            resolve: {
                modules: [
                    'frontend',
                    'node_modules'
                ]
            }
        },
        webpackServer: {
            noInfo: true
        }
    });
};

III. frontend/test/helpers/karma.js

require("babel-polyfill");
var context = require.context('..', true, /_karma\.js$/);
context.keys().forEach(context);

Upvotes: 3

Views: 2819

Answers (1)

TrongBang
TrongBang

Reputation: 967

I solved the problem but eventually got into many problems. Hence decided to make use of ChromeHeadless driver which doesn't require a browser interface to pop up.

config.set({
    basePath: 'frontend',
    browsers: ['ChromeHeadless'],
    files: [
        'karma/**/*_test.js'
    ],
...})

Upvotes: 1

Related Questions