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.
npm install karma-commonjsVerified import paths — ran on the pinned version, not inferred.
This configuration demonstrates how to set up Karma with `karma-commonjs` to test CommonJS modules. It includes the `commonjs` framework and preprocessor, along with an example of configuring `modulesRoot`.
Consider migrating to modern test runners and module bundlers/transpilers (e.g., Jest, Vitest, Web Test Runner with Rollup/Webpack) which offer native ESM/CJS support and better performance.
Ensure every file that acts as a CommonJS module (source or test) is listed in the `files` array and associated with the `commonjs` preprocessor. Failing to do so will result in `require` not being defined for undeclared modules.
If your project relies on advanced Browserify features, consider using `karma-browserify` instead. For simple CommonJS module testing without complex bundling needs, `karma-commonjs` might suffice but be aware of its limitations.
Ensure 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'] }`.Verify 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.