or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-karma-mocha

A Karma plugin adapter for the Mocha testing framework enabling browser-based test execution

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/karma-mocha@2.0.x

To install, run

npx @tessl/cli install tessl/npm-karma-mocha@2.0.0

index.mddocs/

karma-mocha

karma-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.

Package Information

  • Package Name: karma-mocha
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install karma-mocha mocha --save-dev

Core Imports

The 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']
  });
};

Basic Usage

// 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'
      }
    }
  });
};

Architecture

karma-mocha works as a bridge between two testing systems:

  • Karma Framework Integration: Registers as a Karma framework plugin that automatically sets up the test environment
  • File Injection: Automatically includes Mocha library files, CSS, and adapter scripts into the Karma test environment
  • Configuration Processing: Processes Mocha configuration options from Karma config and mocha.opts files
  • Result Reporting: Translates Mocha test results into Karma's result format with detailed metadata
  • Browser Compatibility: Provides polyfills and utilities for cross-browser test execution

Capabilities

Framework Registration

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]
};

Mocha Integration

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);

Configuration Processing

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);

Configuration Options

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'
  }
}

Test Result Reporting

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;
}

Custom Reporter Creation

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);

Test Execution

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);

Error Handling

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);

Utility Functions

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);

Command Line Integration

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=unit

Browser Compatibility

The adapter includes compatibility features:

  • Array.prototype.includes polyfill: For older browsers
  • Date.now polyfill: For IE <= 8
  • Cross-browser DOM manipulation: For reporter node creation

Integration Notes

  • Dependencies: Minimal dependency footprint - only requires minimist as a runtime dependency
  • Peer Dependencies: Requires both karma and mocha to be installed
  • Automatic Setup: No manual initialization required - works through Karma's plugin system
  • File Order: Automatically manages loading order of Mocha files, CSS, and adapter scripts
  • Coverage Support: Compatible with Karma coverage plugins (reports window.__coverage__)
  • Debug Mode: Provides enhanced error display in Karma's debug.html page
  • Configuration Filtering: Automatically filters out internal options (reporter, require, expose) when creating Mocha config