or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-karma-jasmine

A Karma plugin that provides an adapter for the Jasmine testing framework to run tests in browsers

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

To install, run

npx @tessl/cli install tessl/npm-karma-jasmine@4.0.0

index.mddocs/

Karma Jasmine

Karma Jasmine is a Karma plugin that provides an adapter for the Jasmine testing framework. It enables developers to run Jasmine tests in browsers through Karma's automated testing infrastructure, with support for test filtering, sharding, debugging, and comprehensive error reporting.

Package Information

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

Core Imports

This package is configured as a Karma plugin and does not export functions for direct import. Instead, it registers itself with Karma's plugin system when installed.

Basic Usage

Configure karma-jasmine in your Karma configuration:

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],
    
    files: [
      'src/**/*.js',
      'test/**/*.spec.js'
    ],
    
    // Optional jasmine-specific configuration
    client: {
      jasmine: {
        random: true,
        seed: '4321',
        oneFailurePerSpec: true,
        failFast: true,
        timeoutInterval: 1000
      }
    }
  });
};

Run tests with optional filtering:

# Run all tests
karma start

# Run tests matching a pattern
karma start &
karma run -- --grep=<pattern>

Architecture

Karma Jasmine operates through several key components:

  • Plugin Framework: Registers with Karma as both a framework and reporter plugin
  • Jasmine Integration: Configures and initializes Jasmine testing environment in browser contexts
  • Test Filtering: Supports pattern-based filtering, debug mode, and parallel execution (sharding)
  • Custom Reporter: Provides enhanced error reporting with stack trace filtering and debug URLs
  • Boot System: Modified Jasmine boot loader optimized for Karma's test running environment

Capabilities

Framework Registration

Karma Jasmine registers itself as a framework plugin that Karma can use to run Jasmine tests.

// Main module export structure
module.exports = {
  'framework:jasmine': ['factory', initJasmine],
  'reporter:karma-jasmine': ['factory', InjectKarmaJasmineReporter]
};

/**
 * Initializes Jasmine framework for Karma
 * @param {Array} files - Karma files configuration array
 */
function initJasmine(files);

/**
 * Creates reporter for enhanced debugging and error reporting
 * @param {boolean} singleRun - Karma singleRun configuration
 * @returns {Object} Reporter with onSpecComplete handler
 */
function InjectKarmaJasmineReporter(singleRun);

Test Configuration

Configuration options that can be passed to Jasmine through Karma's client configuration.

// Available jasmine configuration options
interface JasmineConfig {
  /** Enable random test execution order */
  random?: boolean;
  /** Seed value for random test order (string or number) */
  seed?: string | number;
  /** Stop execution after first failure per spec */
  oneFailurePerSpec?: boolean;
  /** Stop execution on first test failure */
  failFast?: boolean;
  /** Default timeout interval for async tests in milliseconds */
  timeoutInterval?: number;
  /** Custom spec filter function */
  specFilter?: (spec: any) => boolean;
}

// Client configuration structure
interface KarmaClientConfig {
  jasmine?: JasmineConfig;
  args?: string[];
  shardIndex?: number;
  totalShards?: number;
}

Test Filtering and Pattern Matching

Support for running subsets of tests using various filtering mechanisms.

/**
 * Extract grep pattern from client arguments
 * @param {Array|string} clientArguments - Karma client arguments
 * @returns {string} Grep pattern or empty string
 */
function getGrepOption(clientArguments);

/**
 * Create regular expression from filter pattern
 * @param {string} filter - Filter pattern (supports regex syntax)
 * @returns {RegExp} Compiled regular expression
 */
function createRegExp(filter);

/**
 * Filter specs based on grep pattern
 * @param {Object} clientConfig - Client configuration
 * @param {Array} specs - Array of spec objects
 * @returns {Array|undefined} Filtered specs or undefined if no pattern
 */
function getGrepSpecsToRun(clientConfig, specs);

/**
 * Get single spec for debug mode
 * @param {Object} location - Browser location object
 * @param {Array} specs - Array of spec objects  
 * @returns {Array|undefined} Single spec for debugging or undefined
 */
function getDebugSpecToRun(location, specs);

/**
 * Get specs for current shard in parallel execution
 * @param {Array} specs - Array of spec objects
 * @param {Object} clientConfig - Client configuration with shard info
 * @returns {Array|undefined} Subset of specs for current shard
 */
function getShardedSpecsToRun(specs, clientConfig);

Debug Support

Functionality for debugging individual test failures with enhanced URLs and logging.

/**
 * Generate debug URL for re-running specific test
 * @param {string} description - Test description/name
 * @returns {string} Debug URL with spec parameter
 */
function debugUrl(description);

/**
 * Parse URL query parameters into object
 * @param {Object} location - Browser location object with search property
 * @returns {Object} Parsed query parameters as key-value pairs
 */
function parseQueryParams(location);

Error Handling and Stack Trace Processing

Enhanced error reporting with cleaned stack traces and relevant error information.

/**
 * Format failed test step with cleaned stack trace
 * @param {Object} step - Step object with stack and message properties
 * @returns {string} Formatted error message with relevant stack info
 */
function formatFailedStep(step);

/**
 * Determine if stack entry is external to jasmine/karma frameworks
 * @param {string} entry - Error stack entry line
 * @returns {boolean} True if external to testing frameworks
 */
function isExternalStackEntry(entry);

/**
 * Filter stack traces to show only relevant entries
 * @param {Array} stack - Array of stack frame strings
 * @returns {Array} Filtered array of relevant stack entries
 */
function getRelevantStackFrom(stack);

Karma Reporter Integration

Custom reporter that integrates with Karma's result reporting system and provides enhanced test result handling.

/**
 * Custom Jasmine reporter for Karma integration
 * @param {Object} tc - Karma test context/runner
 * @param {Object} jasmineEnv - Jasmine environment instance
 */
function KarmaReporter(tc, jasmineEnv);

/**
 * Spec filter for controlling which tests run
 * @param {Object} clientConfig - Karma client configuration
 * @param {Object} jasmineEnv - Jasmine environment instance
 */
function KarmaSpecFilter(clientConfig, jasmineEnv);

// KarmaReporter event handlers
interface KarmaReporter {
  /** Called when Jasmine starts test execution */
  jasmineStarted(data: { totalSpecsDefined: number }): void;
  /** Called when Jasmine completes all tests */
  jasmineDone(result: { order?: any, coverage?: any }): void;
  /** Called when a test suite starts */
  suiteStarted(result: { description: string }): void;
  /** Called when a test suite completes */
  suiteDone(result: { description: string, failedExpectations?: any[] }): void;
  /** Called when an individual spec starts */
  specStarted(): void;
  /** Called when an individual spec completes */
  specDone(specResult: SpecResult): void;
}

// Test result structure
interface SpecResult {
  id: string;
  description: string;
  fullName: string;
  status: 'passed' | 'failed' | 'disabled' | 'pending' | 'excluded';
  failedExpectations: Array<{
    message: string;
    stack?: string;
    filename?: string;
    lineno?: number;
  }>;
  passedExpectations: any[];
  properties?: any;
}

Suite Hierarchy Management

Data structures for managing test suite organization and hierarchy.

/**
 * Tree node representing test suite hierarchy
 * @param {string} name - Suite name
 * @param {SuiteNode} parent - Parent suite node
 */
function SuiteNode(name, parent);

interface SuiteNode {
  name: string;
  parent: SuiteNode | null;
  children: SuiteNode[];
  /** Add child suite to this node */
  addChild(name: string): SuiteNode;
}

/**
 * Process suite hierarchy into nested object structure
 * @param {Object} suite - Jasmine suite object
 * @param {Object} pointer - Target object to populate
 */
function processSuite(suite, pointer);

/**
 * Get all spec names organized by suite hierarchy
 * @param {Object} topSuite - Root Jasmine suite
 * @returns {Object} Nested object with suite names and spec arrays
 */
function getAllSpecNames(topSuite);

Types

// Core configuration interfaces
interface KarmaConfig {
  frameworks: string[];
  files: string[];
  client?: {
    jasmine?: JasmineConfig;
    args?: string[];
    shardIndex?: number;
    totalShards?: number;
  };
  singleRun?: boolean;
}

// Test execution result structure  
interface TestResult {
  id: string;
  description: string;
  fullName: string;
  suite: string[];
  success: boolean;
  skipped: boolean;
  disabled: boolean;
  pending: boolean;
  time: number;
  log: string[];
  executedExpectationsCount: number;
  passedExpectations: any[];
  properties?: any;
  debug_url?: string;
}

// Sharding configuration for parallel execution
interface ShardConfig {
  shardIndex: number;
  totalShards: number;
}

// Grep filtering configuration
interface GrepConfig {
  pattern: string;
  flags?: string;
}