CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-karma

Spectacular Test Runner for JavaScript with multi-browser support and plugin architecture.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

configuration.mddocs/

Configuration

Karma's comprehensive configuration system supports multiple file formats and extensive customization options. Configuration files define test execution behavior, file patterns, browser selection, and plugin configuration.

Capabilities

parseConfig Function

Parse and normalize Karma configuration from files and CLI options.

/**
 * Parse Karma configuration from file and CLI options
 * @param configFilePath - Path to configuration file (optional)
 * @param cliOptions - CLI option overrides (optional)
 * @param parseOptions - Parsing behavior options (optional)
 * @returns Configuration object or Promise<Config>
 */
function parseConfig(
  configFilePath?: string,
  cliOptions?: Object,
  parseOptions?: {
    promiseConfig?: boolean;    // Return Promise<Config> instead of Config
    throwErrors?: boolean;      // Throw errors instead of process.exit
  }
): Config | Promise<Config>;

Usage Examples:

const karma = require('karma');

// Parse default configuration file
const config = karma.config.parseConfig();

// Parse specific config file
const config = karma.config.parseConfig('./my-karma.conf.js');

// Parse with CLI overrides
const config = karma.config.parseConfig('./karma.conf.js', {
  singleRun: true,
  browsers: ['Chrome'],
  port: 8080
});

// Async parsing
const config = await karma.config.parseConfig('./karma.conf.js', {}, {
  promiseConfig: true,
  throwErrors: true
});

// Using createPatternObject utility
const pattern = karma.config.createPatternObject({
  pattern: 'test/**/*.js',
  included: true,
  served: true,
  watched: true
});

console.log('Pattern weight:', pattern.weight);
console.log('Is watched:', pattern.watched);

Configuration Object Structure

The main configuration object contains all Karma settings.

/**
 * Main Karma configuration class
 */
class Config {
  // Server configuration
  port: number;                           // Server port (default: 9876)
  hostname: string;                       // Server hostname (default: 'localhost')  
  listenAddress: string;                  // Listen address (default: '0.0.0.0')
  urlRoot: string;                        // URL root path (default: '/')
  protocol: string;                       // Protocol (default: 'http:')
  httpsServerOptions: Object;             // HTTPS server options
  
  // File configuration
  basePath: string;                       // Base path for resolving files
  files: (string | Pattern)[];            // Files to serve and watch
  exclude: string[];                      // Files to exclude
  preprocessors: { [key: string]: string[] }; // File preprocessors
  
  // Browser configuration
  browsers: string[];                     // Browsers to launch
  customLaunchers: { [key: string]: any }; // Custom browser configurations
  browserDisconnectTimeout: number;       // Browser disconnect timeout (default: 2000)
  browserDisconnectTolerance: number;     // Browser disconnect tolerance (default: 0)
  browserNoActivityTimeout: number;       // Browser activity timeout (default: 30000)
  captureTimeout: number;                 // Browser capture timeout (default: 60000)
  
  // Test execution
  singleRun: boolean;                     // Run once and exit (default: false)
  autoWatch: boolean;                     // Watch files for changes (default: true)
  watchOptions: { [key: string]: any };   // File watching options
  restartOnFileChange: boolean;           // Restart on file changes (default: false)
  
  // Reporting
  reporters: string[];                    // Reporters to use (default: ['progress'])
  colors: boolean;                        // Colored output (default: true)
  logLevel: string;                       // Log level (default: 'INFO')
  loggers: any[];                         // Custom loggers
  
  // Framework and plugins
  frameworks: string[];                   // Testing frameworks (e.g., ['jasmine'])
  plugins: string[];                      // Karma plugins to load
  
  // Advanced options
  client: { [key: string]: any };         // Client-side configuration
  middleware: string[];                   // Custom middleware
  proxies: { [key: string]: string };     // URL proxies
  upstreamProxy: { [key: string]: any };  // Upstream proxy configuration
  retryLimit: number;                     // Test retry limit
  detached: boolean;                      // Run in detached mode
  crossOriginAttribute: boolean;          // Add crossorigin attribute to script tags
  failOnEmptyTestSuite: boolean;          // Fail on empty test suite
  concurrency: number;                    // Browser concurrency limit
  
  // Advanced options
  client: { [key: string]: any };         // Client-side configuration
  middleware: string[];                   // Custom middleware
  proxies: { [key: string]: string };     // URL proxies
  upstreamProxy: { [key: string]: any };  // Upstream proxy configuration
  retryLimit: number;                     // Test retry limit (default: 2)
  detached: boolean;                      // Run in detached mode (default: false)
  crossOriginAttribute: boolean;          // Cross-origin attribute (default: true)
  
  // Coverage and reporting
  coverageReporter: { [key: string]: any }; // Coverage reporter configuration
  junitReporter: { [key: string]: any };    // JUnit reporter configuration
  
  // Performance and concurrency
  concurrency: number;                    // Browser concurrency (default: Infinity)
  browserSocketTimeout: number;           // Browser socket timeout (default: 20000)
  pingTimeout: number;                    // Socket.IO ping timeout (default: 5000)
  processKillTimeout: number;             // Process kill timeout (default: 2000)
  
  // File serving
  usePolling: boolean;                    // Use polling for file watching
  pollInterval: number;                   // Polling interval
  httpModule: string;                     // HTTP module to use
  forceJSONP: boolean;                    // Force JSONP transport
  transports: string[];                   // Socket.IO transports
}

Pattern Classes

Karma uses Pattern classes to define how files are handled - whether they're served, included in tests, watched for changes, or cached.

/**
 * File pattern configuration class
 */
class Pattern {
  /**
   * Create new pattern instance
   * @param pattern - File pattern (glob or path)
   * @param served - Serve file to browser (default: true)
   * @param included - Include in test execution (default: true) 
   * @param watched - Watch for changes (default: true)
   * @param nocache - Disable caching (default: false)
   * @param type - File type override
   * @param isBinary - Binary file flag
   * @param integrity - Subresource integrity hash
   */
  constructor(
    pattern: string,
    served?: boolean,
    included?: boolean, 
    watched?: boolean,
    nocache?: boolean,
    type?: string,
    isBinary?: boolean,
    integrity?: string
  );
  
  pattern: string;      // File pattern
  served: boolean;      // File is served to browser
  included: boolean;    // File is included in test run
  watched: boolean;     // File is watched for changes
  nocache: boolean;     // File caching disabled
  weight: number;       // Pattern matching weight
  type?: string;        // MIME type override
  isBinary?: boolean;   // Binary file indicator
  integrity?: string;   // Subresource integrity hash
  
  /**
   * Compare pattern weights for sorting
   * @param other - Other pattern to compare
   * @returns Comparison result
   */
  compare(other: Pattern): number;
}

/**
 * URL pattern for external resources
 * @extends Pattern
 */
class UrlPattern extends Pattern {
  /**
   * Create URL pattern for external resources
   * @param url - URL to external resource
   * @param type - MIME type override
   * @param integrity - Subresource integrity hash
   */
  constructor(url: string, type?: string, integrity?: string);
}

/**
 * Create pattern object from string or configuration
 * @param pattern - Pattern string or configuration object
 * @returns Pattern or UrlPattern instance
 */
function createPatternObject(pattern: string | Object): Pattern | UrlPattern;

Usage Examples:

module.exports = function(config) {
  config.set({
    files: [
      // Simple string patterns
      'src/**/*.js',
      'test/**/*.spec.js',
      
      // Pattern objects
      {
        pattern: 'test/fixtures/**/*.json',
        watched: false,
        included: false,
        served: true
      },
      
      // External URLs
      {
        pattern: 'https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js',
        type: 'js'
      }
    ]
  });
};

Configuration File Examples

Basic configuration file structure for different scenarios.

JavaScript Configuration (karma.conf.js):

module.exports = function(config) {
  config.set({
    // Base path for resolving patterns
    basePath: '',
    
    // Testing framework
    frameworks: ['jasmine'],
    
    // Test files and source files
    files: [
      'src/**/*.js',
      'test/**/*.spec.js'
    ],
    
    // Files to exclude
    exclude: [
      'src/**/*.min.js'
    ],
    
    // Preprocessors for files
    preprocessors: {
      'src/**/*.js': ['coverage'],
      'test/**/*.js': ['babel']
    },
    
    // Reporters
    reporters: ['progress', 'coverage'],
    
    // Coverage configuration
    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    },
    
    // Server configuration
    port: 9876,
    hostname: 'localhost',
    colors: true,
    logLevel: config.LOG_INFO,
    
    // Browser configuration
    browsers: ['Chrome'],
    customLaunchers: {
      ChromeHeadlessCI: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox', '--disable-web-security']
      }
    },
    
    // Test execution
    singleRun: true,
    autoWatch: false,
    concurrency: Infinity,
    
    // Timeouts
    browserDisconnectTimeout: 10000,
    browserNoActivityTimeout: 60000,
    captureTimeout: 60000
  });
};

TypeScript Configuration (karma.conf.ts):

import { Config } from 'karma';

export default function(config: Config) {
  config.set({
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    
    files: [
      'src/**/*.ts',
      'test/**/*.spec.ts'
    ],
    
    preprocessors: {
      'src/**/*.ts': ['typescript', 'coverage'],
      'test/**/*.ts': ['typescript']
    },
    
    typescriptPreprocessor: {
      options: {
        sourceMap: true,
        target: 'ES5',
        module: 'commonjs'
      }
    },
    
    browsers: ['Chrome'],
    singleRun: true
  });
}

Environment-Specific Configuration

Configuration can be customized based on environment variables or CLI arguments.

module.exports = function(config) {
  const isCI = process.env.CI === 'true';
  const isDebug = process.argv.includes('--debug');
  
  config.set({
    browsers: isCI ? ['ChromeHeadless'] : ['Chrome'],
    singleRun: isCI,
    autoWatch: !isCI,
    logLevel: isDebug ? config.LOG_DEBUG : config.LOG_INFO,
    
    // CI-specific settings
    ...(isCI && {
      browserDisconnectTolerance: 3,
      browserNoActivityTimeout: 90000,
      captureTimeout: 90000
    })
  });
};

Plugin Configuration

Configure various Karma plugins through the configuration object.

// Common plugin configurations
interface PluginConfigurations {
  // Coverage plugin
  coverageReporter: {
    type: 'html' | 'lcov' | 'text' | 'cobertura';
    dir: string;
    subdir?: string;
    file?: string;
    check?: {
      global: {
        statements: number;
        branches: number;
        functions: number;
        lines: number;
      };
    };
  };
  
  // JUnit reporter
  junitReporter: {
    outputDir: string;
    outputFile: string;
    suite: string;
    useBrowserName: boolean;
  };
  
  // Browser stack launcher
  browserStack: {
    username: string;
    accessKey: string;
    project: string;
    build: string;
  };
  
  // Webpack preprocessor  
  webpack: {
    // Webpack configuration object
  };
  
  // Istanbul instrumenter
  coverageIstanbulReporter: {
    reports: string[];
    dir: string;
    combineBrowserReports: boolean;
    fixWebpackSourcePaths: boolean;
  };
}

Usage Examples:

module.exports = function(config) {
  config.set({
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-coverage',
      'karma-webpack'
    ],
    
    // Coverage configuration
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/',
      check: {
        global: {
          statements: 80,
          branches: 75,
          functions: 80,
          lines: 80
        }
      }
    },
    
    // Webpack configuration
    webpack: {
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'babel-loader'
          }
        ]
      }
    }
  });
};

docs

cli-interface.md

configuration.md

index.md

plugin-system.md

programmatic-api.md

tile.json