Zum Inhalt springen

Karma

Karma is a test runner designed to work with any testing framework and is particularly useful for JavaScript testing across multiple browsers.

Installation

npm install --save-dev karma karma-chrome-launcher karma-jasmine jasmine-core

Setup

Initialize Karma

# Interactive setup
npx karma init

# Answer prompts:
# - Framework: jasmine
# - Browser: Chrome
# - Test files: test/**/*-test.js

karma.conf.js

module.exports = function(config) {
  config.set({
    // Base path
    basePath: '',

    // Testing frameworks
    frameworks: ['jasmine'],

    // Files to include
    files: [
      'src/**/*.js',
      'test/**/*-test.js'
    ],

    // Files to exclude
    exclude: [],

    // Preprocess files
    preprocessors: {
      'src/**/*.js': ['coverage'],
      'test/**/*.js': ['babel']
    },

    // Reporters
    reporters: ['progress', 'coverage'],

    // Coverage reporter
    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    },

    // Port
    port: 9876,

    // Colors in output
    colors: true,

    // Logging level
    logLevel: config.LOG_INFO,

    // Auto watch
    autoWatch: true,

    // Browsers to test
    browsers: ['Chrome'],

    // CI mode
    singleRun: false,

    // Concurrency level
    concurrency: Infinity
  });
};

Running Tests

# Start Karma (watch mode)
npx karma start

# Run tests once
npx karma start --single-run

# Run with specific browser
npx karma start --browsers Chrome

# Run with multiple browsers
npx karma start --browsers Chrome,Firefox

# Run with coverage
npx karma start --reporters coverage

Writing Tests

Jasmine Example

describe('Calculator', function() {
  let calculator;

  beforeEach(function() {
    calculator = new Calculator();
  });

  describe('add method', function() {
    it('should add two numbers', function() {
      expect(calculator.add(2, 3)).toBe(5);
    });

    it('should handle negative numbers', function() {
      expect(calculator.add(-1, 3)).toBe(2);
    });
  });

  describe('subtract method', function() {
    it('should subtract two numbers', function() {
      expect(calculator.subtract(5, 3)).toBe(2);
    });
  });
});

Configuration Options

OptionDescription
basePathBase path for file resolution
frameworksTesting frameworks to use
filesFiles to load in browser
excludeFiles to exclude
preprocessorsPreprocess files
reportersReport results
portKarma server port
browsersBrowsers to test
singleRunRun once and exit
autoWatchWatch files for changes

Browser Launchers

# Install additional browsers
npm install --save-dev karma-firefox-launcher
npm install --save-dev karma-safari-launcher
npm install --save-dev karma-edge-launcher

# Configure in karma.conf.js
browsers: ['Chrome', 'Firefox', 'Safari']

Preprocessors

Babel

npm install --save-dev karma-babel-preprocessor @babel/core @babel/preset-env
preprocessors: {
  'src/**/*.js': ['babel'],
  'test/**/*.js': ['babel']
},
babelPreprocessor: {
  options: {
    presets: ['@babel/preset-env']
  }
}

Coverage

npm install --save-dev karma-coverage
preprocessors: {
  'src/**/*.js': ['coverage']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
  type: 'html',
  dir: 'coverage/'
}

Reporters

Available Reporters

# Progress
npm install --save-dev karma-spec-reporter

# JUnit (for CI)
npm install --save-dev karma-junit-reporter

# Detailed results
npm install --save-dev karma-spec-reporter

# Coverage
npm install --save-dev karma-coverage

Configuration

reporters: ['progress', 'spec', 'coverage'],

specReporter: {
  maxLogLines: 5,
  suppressErrorSummary: false,
  suppressFailed: false,
  suppressPassed: false,
  showSpecTiming: true
},

junitReporter: {
  outputDir: 'test-results/',
  outputFile: 'test-results.xml'
}

CI/CD Integration

GitHub Actions

name: Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '16'
      - run: npm ci
      - run: npm run test:ci

package.json

{
  "scripts": {
    "test": "karma start",
    "test:ci": "karma start --single-run --no-auto-watch --reporters junit,coverage"
  }
}

Watch Mode Configuration

// Automatically re-run tests on file changes
autoWatch: true,
autoWatchBatchDelay: 300,

// Specify files to watch
files: [
  {pattern: 'src/**/*.js', watched: true},
  {pattern: 'test/**/*.js', watched: true},
  {pattern: 'node_modules/**/*.js', watched: false}
]

Debugging Tests

# Run with verbose logging
npx karma start --log-level DEBUG

# Open debug page in browser
# Go to: http://localhost:9876/debug.html

# Run single file
npx karma run -- --grep "Calculator"

# Inspect in browser DevTools
# Debug button opens Chrome DevTools

Best Practices

  • Keep test files alongside source code
  • Use meaningful test descriptions
  • Test edge cases and error conditions
  • Maintain test isolation with beforeEach/afterEach
  • Mock external dependencies
  • Keep tests focused and independent
  • Use code coverage to find untested code
  • Integrate Karma into CI/CD pipeline

Resources


Last updated: 2025-07-06|Edit on GitHub