Karma CommonJS Plugin
The `karma-commonjs` plugin facilitates the testing of JavaScript modules written in the CommonJS format within a Karma test runner environment. Rather than bundling, it applies a lightweight wrapper to individual modules, allowing them to interpret `require()` calls directly in the browser. The current stable version, 1.0.0, was last updated in 2016, making it effectively abandoned, especially given that its primary peer dependency, Karma, has also been officially deprecated since 2024. While `karma-commonjs` boasts potentially faster reloads for individual file changes and provides cleaner stack traces by avoiding full bundling, it requires developers to manually list all module files in the Karma configuration. This contrasts with more modern alternatives like `karma-browserify`, which leverage bundlers to automatically discover and include dependencies while also supporting the full Browserify API for transforms and Node.js shims.
Common errors
-
ReferenceError: require is not defined
cause A file attempting to use `require()` was not processed by the `commonjs` preprocessor, or a required module was not included in Karma's `files` configuration.fixEnsure the file (and its dependencies) are listed in `karma.conf.js` within the `files` array and have the `commonjs` preprocessor applied: `preprocessors: { 'path/to/my-module.js': ['commonjs'] }`. -
Error: Cannot find module 'some-module'
cause The module being `require()`d is not found at the expected path, or the `commonjsPreprocessor.modulesRoot` is incorrectly configured.fixVerify the module's path is correct relative to the file requiring it, or adjust the `commonjsPreprocessor.modulesRoot` option in `karma.conf.js` to point to the directory containing your modules.
Warnings
- breaking The underlying Karma test runner is officially deprecated. `karma-commonjs` is not actively maintained and is unlikely to receive updates or security fixes.
- gotcha Unlike bundler-based solutions (e.g., `karma-browserify`), `karma-commonjs` requires you to explicitly specify ALL CommonJS module files in the `files` array and `preprocessors` configuration within `karma.conf.js`. It does not automatically discover `require()`d dependencies.
- gotcha `karma-commonjs` provides a simpler CommonJS wrapping mechanism but lacks the full feature set of a bundler like Browserify. It does not natively support Browserify transforms, plugins, or shims for Node.js core modules.
Install
-
npm install karma-commonjs -
yarn add karma-commonjs -
pnpm add karma-commonjs
Imports
- commonjs
import { commonjs } from 'karma-commonjs';// karma.conf.js module.exports = function(config) { config.set({ frameworks: ['jasmine', 'commonjs'], // ... }); }; - commonjs preprocessor
const commonjsPreprocessor = require('karma-commonjs');// karma.conf.js module.exports = function(config) { config.set({ // ... preprocessors: { '**/*.js': ['commonjs'] } }); }; - commonjsPreprocessor.modulesRoot
config.commonjs.modulesRoot = 'src';
// karma.conf.js module.exports = function(config) { config.set({ // ... commonjsPreprocessor: { modulesRoot: 'src/modules' } }); };
Quickstart
const path = require('path');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'commonjs'],
files: [
// Your source files (e.g., 'src/**/*.js')
'test/lib.js',
'test/**/*.spec.js'
],
exclude: [],
preprocessors: {
'test/lib.js': ['commonjs'],
'test/**/*.spec.js': ['commonjs']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
concurrency: Infinity,
// Optional configuration for commonjsPreprocessor
commonjsPreprocessor: {
modulesRoot: path.resolve(__dirname, 'src') // Example: look for required modules in 'src' folder
}
});
};
// Example test/lib.js:
// module.exports = { greet: (name) => `Hello, ${name}!` };
// Example test/lib.spec.js:
// const { greet } = require('./lib');
// describe('greet', () => {
// it('should return a greeting', () => {
// expect(greet('World')).toBe('Hello, World!');
// });
// });