karma-webpack

raw JSON →
5.0.1 verified Sat Apr 25 auth: no javascript

Karma plugin that uses webpack to preprocess test files. Current stable version is 5.0.1, released February 2024, with a release cadence of roughly major versions every 1-2 years. It provides both a Karma framework and preprocessor, bundling test files and dependencies into shared bundles and chunks via webpack 5. Key differentiators: seamless integration of webpack with Karma's test runner, automatic handling of multiple outputs, and support for TypeScript out of the box. Requires webpack ^5.0.0 as a peer dependency and Node >=18.

error Error: No provider for "framework:webpack"!
cause Missing 'karma-webpack' plugin in plugins array or not installed
fix
Add 'karma-webpack' to the plugins list: plugins: ['karma-webpack', ...]
error Error: Module not found: Error: Can't resolve 'webpack'
cause Webpack not installed or peer dependency not satisfied
fix
Run npm install webpack@^5.0.0 --save-dev
error TypeError: Cannot read properties of undefined (reading 'length')
cause webpackMiddleware config not provided or empty
fix
Provide webpackMiddleware config: webpackMiddleware: { noInfo: true } or similar
error Error: [webpack-cli] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
cause Webpack config contains options not compatible with webpack 5
fix
Update webpack config to be webpack 5 compatible (e.g., use optimization.splitChunks correctly)
breaking Node >= 18 required starting from v5.0.0
fix Upgrade Node.js to version 18 or higher
breaking Webpack 5 peer dependency required from v5.0.0-alpha.5 onward
fix Update webpack to ^5.0.0
deprecated The .watch() method is deprecated since v5.0.0-alpha.4
fix Use webpack's built-in watch mode via Karma's autoWatch instead
gotcha Files must set 'watched: false' to avoid conflicts with webpack's own watch
fix Set { pattern: 'test/**/*.test.js', watched: false } in karma files config
gotcha Do not specify webpack entry option; Karma-webpack manages entries automatically
fix Remove entry from webpack config; let karma-webpack handle it
npm install karma-webpack
yarn add karma-webpack
pnpm add karma-webpack

Configures Karma to use webpack as both framework and preprocessor for test files with a basic webpack setup.

// karma.conf.js
module.exports = (config) => {
  config.set({
    frameworks: ['mocha', 'webpack'],
    plugins: ['karma-webpack', 'karma-mocha'],
    files: [
      { pattern: 'test/**/*.test.js', watched: false }
    ],
    preprocessors: {
      'test/**/*.test.js': ['webpack']
    },
    webpack: {
      mode: 'development',
      module: {
        rules: [
          { test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' }
        ]
      }
    },
    browsers: ['ChromeHeadless'],
    singleRun: true
  });
};