or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-interface.mdconfiguration.mdindex.mdplugin-system.mdprogrammatic-api.md
tile.json

tessl/npm-karma

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

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

To install, run

npx @tessl/cli install tessl/npm-karma@6.4.0

index.mddocs/

Karma Test Runner

Karma is a sophisticated JavaScript test runner that enables developers to execute JavaScript tests across multiple real browsers simultaneously. It provides a comprehensive testing environment with file watching, automatic test re-runs, and extensive browser support through a plugin architecture.

Package Information

  • Package Name: karma
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install karma --save-dev

Core Imports

const karma = require('karma');
const { Server, runner, stopper, launcher, config, constants } = require('karma');

ES6 modules:

import karma from 'karma';
import { Server, runner, stopper, launcher, config, constants } from 'karma';

Basic Usage

const karma = require('karma');

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

// Create and start server
const server = new karma.Server(config, (exitCode) => {
  console.log('Karma has exited with', exitCode);
  process.exit(exitCode);
});

server.start();

Architecture

Karma's architecture consists of several key components:

  • Test Server: HTTP server that serves test files and coordinates test execution
  • Browser Management: Launches and manages multiple browser instances for testing
  • File System: Watches source files and test files for changes, with preprocessing support
  • Plugin System: Extensible architecture for browsers, frameworks, reporters, and preprocessors
  • CLI Interface: Command-line tools for configuration, running tests, and server management
  • Configuration System: Flexible configuration with JavaScript, TypeScript, and JSON support

Capabilities

Programmatic API

Core programmatic interfaces for server management, test execution, and browser control. Ideal for build tools and custom test runners.

// Main server class for managing test environment
class Server extends EventEmitter {
  constructor(cliOptionsOrConfig: Config | Object, done?: Function); // Automatically starts server
  stop(): Promise<void>;
  refreshFiles(): Promise<void>;
  refreshFile(path: string): Promise<void>;
  get(token: string): any;
  emitExitAsync(code: number): Promise<void>;
}

// Test runner functions
function runner.run(cliOptionsOrConfig: Config | Object, done?: Function): EventEmitter;
function stopper.stop(cliOptionsOrConfig: Config | Object, done?: Function): void;

// Launcher for managing browser instances
class Launcher {
  constructor(server: Server, emitter: EventEmitter, injector: any);
  launch(browsers: string[], concurrency: number): Promise<void>;
  launchSingle(protocol: string, hostname: string, port: number, urlRoot: string, upstreamProxy: any, processKillTimeout: number): Browser;
  kill(id: string): boolean;
  restart(id: string): boolean;
  killAll(): Promise<void>;
  areAllCaptured(): boolean;
  markCaptured(id: string): void;
}

// Constants and version information  
const constants: {
  VERSION: string;
  DEFAULT_PORT: number;
  DEFAULT_HOSTNAME: string;
  DEFAULT_LISTEN_ADDR: string;
  LOG_DISABLE: string;
  LOG_ERROR: string;
  LOG_WARN: string;
  LOG_INFO: string;
  LOG_DEBUG: string;
  LOG_LOG: string;
  LOG_PRIORITIES: string[];
  COLOR_PATTERN: string;
  NO_COLOR_PATTERN: string;
  CONSOLE_APPENDER: object;
  EXIT_CODE: string;
};

Programmatic API

CLI Interface

Command-line interface for interactive development and CI/CD integration. Supports project initialization, test execution, and server management.

// Available CLI commands
karma init [configFile]    // Initialize configuration file  
karma start [configFile]   // Start server and/or run tests
karma run [configFile]     // Trigger test run on existing server
karma stop [configFile]    // Stop running server
karma completion          // Generate shell completion

CLI Interface

Configuration System

Comprehensive configuration system supporting multiple formats and extensive customization options.

function config.parseConfig(
  configFilePath?: string,
  cliOptions?: Object,
  parseOptions?: {
    promiseConfig?: boolean;
    throwErrors?: boolean;
  }
): Config | Promise<Config>;

// Configuration pattern classes
class Pattern {
  constructor(pattern: string, served?: boolean, included?: boolean, watched?: boolean, nocache?: boolean, type?: string, isBinary?: boolean, integrity?: string);
  pattern: string;
  served: boolean;
  included: boolean;
  watched: boolean;
  nocache: boolean;
  weight: number;
  type?: string;
  isBinary?: boolean;
  integrity?: string;
  compare(other: Pattern): number;
}

class UrlPattern extends Pattern {
  constructor(url: string, type?: string, integrity?: string);
}

function createPatternObject(pattern: string | object): Pattern | UrlPattern;

class Config {
  // Core configuration properties
  port: number;
  hostname: string;
  basePath: string;
  frameworks: string[];
  files: (string | Pattern)[];
  exclude: string[];
  browsers: string[];
  reporters: string[];
  // ... extensive configuration options
}

Configuration

Plugin System

Extensible plugin architecture supporting custom browsers, reporters, preprocessors, and frameworks.

// Plugin registration and resolution
function plugin.resolve(plugins: string[], emitter: EventEmitter): any[];
function plugin.createInstantiatePlugin(injector: any): Function;

// Built-in plugin categories
interface PluginTypes {
  'launcher': BrowserLauncher;      // Browser launchers
  'reporter': Reporter;             // Test result reporters  
  'preprocessor': Preprocessor;     // File preprocessors
  'framework': Framework;           // Testing frameworks
  'middleware': Middleware;         // Custom middleware
}

Plugin System

Constants and Utilities

Core constants, version information, and utility functions for configuration and integration.

// Version and default configuration constants
const VERSION: string;
const DEFAULT_PORT: number;
const DEFAULT_HOSTNAME: string;
const DEFAULT_LISTEN_ADDR: string;

// Logging level constants
const LOG_DISABLE: string;
const LOG_ERROR: string;
const LOG_WARN: string;
const LOG_INFO: string;
const LOG_DEBUG: string;
const LOG_LOG: string;
const LOG_PRIORITIES: string[];

// Logger configuration
const COLOR_PATTERN: string;
const NO_COLOR_PATTERN: string;
const CONSOLE_APPENDER: {
  type: string;
  layout: {
    type: string;
    pattern: string;
  };
};

// Internal constants
const EXIT_CODE: string;

Types

interface Config {
  // Server configuration
  port: number;
  hostname: string;
  listenAddress: string;
  urlRoot: string;
  
  // File configuration
  basePath: string;
  files: (string | Pattern)[];
  exclude: string[];
  preprocessors: { [key: string]: string[] };
  
  // Browser configuration
  browsers: string[];
  customLaunchers: { [key: string]: any };
  browserDisconnectTimeout: number;
  browserDisconnectTolerance: number;
  browserNoActivityTimeout: number;
  captureTimeout: number;
  
  // Test execution
  singleRun: boolean;
  autoWatch: boolean;
  watchOptions: { [key: string]: any };
  
  // Reporting
  reporters: string[];
  colors: boolean;
  logLevel: string;
  
  // Framework and plugins
  frameworks: string[];
  plugins: string[];
  
  // Advanced options
  client: { [key: string]: any };
  middleware: string[];
  proxies: { [key: string]: string };
  upstreamProxy: { [key: string]: any };
  retryLimit: number;
  detached: boolean;
  crossOriginAttribute: boolean;
}

interface Pattern {
  pattern: string;
  served: boolean;
  included: boolean;
  watched: boolean;
  nocache: boolean;
  weight: number;
  type?: string;
  isBinary?: boolean;
  integrity?: string;
  compare(other: Pattern): number;
}

interface UrlPattern extends Pattern {
  // Inherits all Pattern properties but with specific defaults for URLs
}

interface File {
  path: string;              // Served path (may be processed)
  originalPath: string;      // Original absolute path
  contentPath: string;       // Content storage path
  mtime: Date;              // Last modified time
  isUrl: boolean;           // Is external URL
  doNotCache: boolean;      // Disable caching
  type?: string;            // MIME type
  isBinary?: boolean;       // Binary file flag
  integrity?: string;       // Subresource integrity hash
  encodings: { [key: string]: Buffer }; // Encoded content cache
}

interface Browser {
  id: string;               // Unique browser ID
  fullName: string;         // Full browser name with version
  name: string;             // Short browser name
  state: string;            // Current browser state
  lastResult: BrowserResult; // Last test execution result
  disconnectsCount: number; // Number of disconnections
  activeSockets: Socket[];  // Active socket connections
  noActivityTimeout: number; // No activity timeout
  singleRun: boolean;       // Single run mode
  
  // Methods
  init(): void;
  setState(state: string): void;
  disconnect(reason?: string): void;
  reconnect(newSocket: Socket): void;
  execute(config: any): void;
  refresh(): Promise<void>;
  serialize(): object;
}

interface BrowserResult {
  id: string;
  fullName: string;
  name: string;
  state: string;
  lastResult: {
    success: number;
    failed: number;
    skipped: number;
    total: number;
    totalTime: number;
    netTime: number;
    error: boolean;
    disconnected: boolean;
  };
}