Search code examples
webpackkarma-runnerkarma-webpack

How to use webpack multiple entries with karma?


I have webpack config with multiple entries:

entry: {
  'js/app': ['./css/app/style.scss', './js/app/index.js'],
  'js/vendor': ['./js/vendor/index.js', './css/vendor/index.css'],
  'js/snippets': './js/snippets/index.js'
},

and I don't want to hardcode all this paths in karma config. Just include webpack config and connect all the entries from there:

var webpackConfig = require('./webpack.config');
...
...
files: webpackConfig.entry,

but file option expect to have an array of strings. Is there any ready solution for it? Not to convert object to array manually.


Solution

  • I have a similar setup, here's what worked for me. In the karma config file, for the files just config your tests. For me it was something like this:

    files: [
      './scripts/vendor/jquery.min.js',
      // any other global dependency
      './scripts/**/*.spec.js'
    ]
    

    edit

    Because of how webpack works, you don't need to add your project files in the karma configuration. Just by the fact that your test will import/require the test subject file, webpack will bundle it and the test will run.

    endedit

    Then in the preprocessors section:

    preprocessors: {
      './scripts/**/*.spec.js': ['webpack']
    },
    

    Finally, I have imported the webpack configuration:

    const webpackConfig = require('./webpack.config.js');
    

    And using the karma-webpack plugin I added a webpack section as follows:

    webpack: {
      devtool: webpackConfig.devtool,
      resolve: webpackConfig.resolve,
      module: webpackConfig.module,
      externals: Object.assign({}, webpackConfig.externals, {
        chai: 'chai'
      })
    },