A Karma plugin adapter for the Mocha testing framework enabling browser-based test execution
npx @tessl/cli install tessl/npm-karma-mocha@2.0.0karma-mocha is a Karma plugin that serves as an adapter for the Mocha testing framework. It enables developers to run Mocha tests within the Karma test runner environment, providing seamless integration between Karma's browser-based test execution platform and Mocha's behavior-driven development testing capabilities.
npm install karma-mocha mocha --save-devThe package registers itself as a Karma framework plugin - no direct imports needed in test files:
// karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['mocha'], // karma-mocha registers the 'mocha' framework
files: ['test/**/*.js']
});
};// karma.conf.js - Basic configuration
module.exports = function(config) {
config.set({
frameworks: ['mocha'],
files: ['test/**/*.spec.js'],
browsers: ['Chrome']
});
};With Mocha configuration options:
// karma.conf.js - With Mocha options
module.exports = function(config) {
config.set({
frameworks: ['mocha'],
files: ['test/**/*.spec.js'],
browsers: ['Chrome'],
client: {
mocha: {
ui: 'bdd',
timeout: 5000,
reporter: 'html'
}
}
});
};karma-mocha works as a bridge between two testing systems:
The plugin automatically registers with Karma as the 'mocha' framework.
/**
* Karma framework plugin registration
* Automatically called by Karma when 'mocha' is specified in frameworks array
*/
const frameworkPlugin = {
'framework:mocha': ['factory', initMocha]
};Core function that sets up Mocha within the Karma environment.
/**
* Initialize Mocha framework integration with Karma
* @param files - Karma files array to inject Mocha dependencies
* @param config - Karma configuration object
*/
function initMocha(files, config);Processes and normalizes Mocha configuration options.
/**
* Process Mocha configuration options including loading from mocha.opts files
* @param mochaConfig - Mocha configuration object
* @returns Normalized configuration object with supported Mocha options
*/
function getMochaOpts(mochaConfig);The following Mocha options are supported via client.mocha in Karma configuration:
interface MochaConfig {
/** Mocha reporter to use (e.g., 'html', 'dot') */
reporter?: string;
/** Mocha user interface (e.g., 'bdd', 'tdd') */
ui?: string;
/** Files to require before running tests */
require?: string[];
/** Global variables to allow in tests */
globals?: string[];
/** Pattern to filter tests */
grep?: string | RegExp;
/** Test timeout in milliseconds */
timeout?: number;
/** Slow test threshold in milliseconds */
slow?: number;
/** Stop running tests after first failure */
bail?: boolean;
/** Ignore global variable leaks */
ignoreLeaks?: boolean;
/** Path to mocha.opts file or true for default location */
opts?: string | boolean;
/** Test properties to expose in test results */
expose?: string[];
}Configuration Examples:
// Basic Mocha configuration
client: {
mocha: {
ui: 'bdd',
timeout: 10000,
reporter: 'html'
}
}
// With grep pattern filtering
client: {
mocha: {
grep: 'integration',
bail: true
}
}
// With custom requires and exposed properties
client: {
mocha: {
require: ['should', './test/helpers.js'],
expose: ['body', 'state']
}
}
// Using mocha.opts file
client: {
mocha: {
opts: 'test/mocha.opts' // or true for default 'test/mocha.opts'
}
}Transforms Mocha test results into Karma's expected format.
/**
* Report individual test result to Karma
* @param karma - Karma test context
* @param test - Mocha test object
*/
function reportTestResult(karma, test);
interface KarmaTestResult {
/** Test ID (empty string) */
id: string;
/** Test title */
description: string;
/** Array of parent suite titles */
suite: string[];
/** True if test passed */
success: boolean;
/** True if test was skipped */
skipped: boolean;
/** True if test is pending (same as skipped) */
pending: boolean;
/** Test duration in milliseconds */
time: number;
/** Array of error messages */
log: string[];
/** Array of detailed assertion error objects */
assertionErrors: AssertionError[];
/** Test start timestamp */
startTime: number;
/** Test end timestamp */
endTime: number;
/** Optional exposed Mocha properties (if configured) */
mocha?: Record<string, any>;
}
interface AssertionError {
/** Error name */
name: string;
/** Error message */
message: string;
/** Actual data in assertion, serialized to string */
actual?: string;
/** Expected data in assertion, serialized to string */
expected?: string;
/** True if configured to show diff */
showDiff?: boolean;
}Creates Mocha reporter tailored for Karma integration.
/**
* Create custom Mocha reporter constructor for Karma integration
* @param karma - Karma test context
* @param pathname - Window location pathname
* @returns Mocha reporter constructor function
*/
function createMochaReporterConstructor(karma, pathname);Handles Mocha test execution with command-line argument support.
/**
* Create start function for Mocha test execution with grep support
* @param mocha - Mocha instance
* @returns Function to start test execution with configuration
*/
function createMochaStartFn(mocha);
/**
* Create Mocha configuration object from Karma config
* Note: Filters out 'reporter', 'require', and 'expose' properties
* @param karma - Karma context with configuration
* @returns Mocha configuration object
*/
function createConfigObject(karma);The adapter provides enhanced error formatting and processing:
/**
* Format test errors, removing Mocha stack entries
* @param error - Error object from test failure
* @returns Formatted error string
*/
function formatError(error);
/**
* Process assertion errors for better reporting with diff support
* @param error - Assertion error object
* @returns Processed error object with diff information
*/
function processAssertionError(error);Internal utility functions that support the adapter functionality:
/**
* Create Karma file pattern object for dependency injection
* @param path - File path to include
* @returns Karma pattern object with default options
*/
function createPattern(path);
/**
* Check if Karma configuration contains Mocha options
* @param karma - Karma context object
* @returns True if mocha configuration exists
*/
function haveMochaConfig(karma);
/**
* Create DOM node for Mocha reporter in debug mode
* Creates div element with id='mocha' and appends to document.body
*/
function createMochaReporterNode();
/**
* Polyfill for Array.prototype.includes compatibility
* @param collection - Array or string to search
* @param element - Element to find
* @param startIndex - Starting search index
* @returns True if element is found
*/
function includes(collection, element, startIndex);
/**
* Polyfill for Array.prototype.reduce functionality
* @param array - Array to reduce
* @param reducer - Reducer function
* @param memo - Initial accumulator value
* @returns Final reduced value
*/
function arrayReduce(array, reducer, memo);karma-mocha supports Mocha's grep functionality through Karma's command line:
# Run only tests matching pattern
karma start &
karma run -- --grep="integration tests"
# Or with specific pattern format
karma run -- --grep=unitThe adapter includes compatibility features:
minimist as a runtime dependencykarma and mocha to be installedwindow.__coverage__)reporter, require, expose) when creating Mocha config