### Install Karma plugins and initialize configuration Source: https://karma-runner.github.io/6.4/plus/emberjs.html Install the required Karma plugins and generate a configuration file. The npm install commands add the QUnit adapter and the Ember preprocessor, and 'karma init' walks through the basic setup. ```bash npm install karma-qunit --save-dev ``` ```bash npm install karma-ember-preprocessor --save-dev ``` ```bash karma init ``` -------------------------------- ### server.start() Source: https://karma-runner.github.io/6.4/dev/public-api.html Starts the Karma server. This method is equivalent to the `karma start` command. ```APIDOC ## server.start() ### Description Starts the Karma server, equivalent to running `karma start` from the command line. ### Method start ### Usage ``` server.start() ``` ``` -------------------------------- ### Directory tree example Source: https://karma-runner.github.io/6.4/plus/requirejs.html Shows the example project structure with karma.conf.js, test-main.js, and other files. ```bash $ tree . |-- index.html |-- karma.conf.js |-- lib | |-- jquery.js | |-- require.js | `-- underscore.js |-- src | |-- app.js | `-- main.js `-- test |-- appSpec.js `-- test-main.js 3 directories, 9 files ``` -------------------------------- ### Start Karma server Source: https://karma-runner.github.io/6.4/dev/public-api.html Starts the Karma server, equivalent to running `karma start` from the command line. ```javascript server.start() ``` -------------------------------- ### Run Karma with PhantomJS Source: https://karma-runner.github.io/6.4/plus/cloud9.html Installs the PhantomJS launcher plugin and starts Karma with PhantomJS as the browser. ```bash # Install the PhantomJS plugin: $ npm install karma-phantomjs-launcher # Start Karma: $ karma start --browsers PhantomJS ``` -------------------------------- ### Install karma-cli Source: https://karma-runner.github.io/6.4/about/migration.html Install the command line interface to use the karma command. ```bash npm install -g karma-cli ``` -------------------------------- ### Start Karma with a configuration file Source: https://karma-runner.github.io/6.4/intro/configuration.html Starts Karma using the specified configuration file. If no file is given, Karma looks for `karma.conf.js` or `karma.conf.coffee` in the current directory. ```bash # Start Karma using your configuration: $ karma start my.conf.js ``` -------------------------------- ### Initialize Karma with karma init Source: https://karma-runner.github.io/6.4/plus/requirejs.html Command to start the interactive Karma configuration wizard. ```bash $ karma init ``` -------------------------------- ### Configure CoffeeScript preprocessor in Karma config Source: https://karma-runner.github.io/6.4/config/preprocessors.html Example configuration file that sets up the 'coffee' preprocessor for CoffeeScript files. This is the typical usage after installing the plugin. ```javascript module.exports = function(config) { config.set({ preprocessors: { '**/*.coffee': ['coffee'] } }); }; ``` -------------------------------- ### Install karma-firefox-launcher Source: https://karma-runner.github.io/6.4/config/browsers.html Install the Firefox launcher plugin via npm before adding Firefox to the browsers array. ```bash # Install the launcher first with npm: $ npm install karma-firefox-launcher --save-dev ``` -------------------------------- ### Install karma-teamcity-reporter Source: https://karma-runner.github.io/6.4/plus/teamcity.html Installs the karma-teamcity-reporter package as a development dependency using npm. ```bash npm i --save-dev karma-teamcity-reporter ``` -------------------------------- ### Upgrade to constructor-based server API (after) Source: https://karma-runner.github.io/6.4/about/changelog.html New way to start the Karma server after version 0.13.0. Use the Server constructor and call start() on the instance. ```javascript var Server = require(‘karma’).Server var server = new Server(config, done) server.start() ``` -------------------------------- ### Install karma-cli globally Source: https://karma-runner.github.io/6.4/intro/installation.html Installs karma-cli globally to run Karma from the command line; required on Windows. ```bash $ npm install -g karma-cli ``` -------------------------------- ### Preprocessors execution order example Source: https://karma-runner.github.io/6.4/config/preprocessors.html Shows a simple preprocessors config where 'a' is executed before 'b' for '*.js' files. ```javascript preprocessors: { '*.js': ['a', 'b'] } ``` -------------------------------- ### Start Karma test runner Source: https://karma-runner.github.io/6.4/plus/requirejs.html Run this command to start Karma and execute tests. If not configured to watch files, use 'karma run' to trigger manually. ```bash $ karma start ``` -------------------------------- ### Configure package.json for Karma with PhantomJS Source: https://karma-runner.github.io/6.4/plus/semaphore.html Example package.json configuration for running Karma tests with PhantomJS on Semaphore. Includes the karma devDependency and a test script that starts Karma in single-run mode with PhantomJS. ```json // ...snip... "devDependencies": { "karma": "~0.10" }, // ...snip... "scripts": { "test": "./node_modules/.bin/karma start --single-run --browsers PhantomJS" } // ...snip... ``` -------------------------------- ### httpsServerOptions example Source: https://karma-runner.github.io/6.4/config/configuration-file.html Configures HTTPS server options with key and cert read from files. Use this to enable HTTPS in Karma. ```javascript httpsServerOptions: { key: fs.readFileSync('server.key', 'utf8'), cert: fs.readFileSync('server.crt', 'utf8') }, ``` -------------------------------- ### Partial order preprocessor example Source: https://karma-runner.github.io/6.4/config/preprocessors.html Shows a config where 'a' runs first, 'd' runs last, but 'b' and 'c' order is arbitrary. ```javascript preprocessors: { '*.js': ['a', 'b', 'c'], 'a.*': ['c', 'b', 'd'] } ``` -------------------------------- ### Install karma-coffee-preprocessor Source: https://karma-runner.github.io/6.4/config/preprocessors.html Install the CoffeeScript preprocessor plugin via npm. This is required before using the 'coffee' preprocessor. ```bash # Install it first with npm $ npm install karma-coffee-preprocessor --save-dev ``` -------------------------------- ### Karma files configuration complete example Source: https://karma-runner.github.io/6.4/config/files.html Complete example of the `files` configuration array in a Karma config file. Shows detailed patterns with options like `watched`, `served`, `included`, and `nocache`, plus a simple string pattern equivalent to `{pattern: 'test/unit/*.spec.js', watched: true, served: true, included: true}`. Note that with the html2js preprocessor, HTML files are referenced as `window.__html__['compiled/index.html']`. ```javascript files: [ // Detailed pattern to include a file. Similarly other options can be used { pattern: 'lib/angular.js', watched: false }, // Prefer to have watched false for library files. No need to watch them for changes // simple pattern to load the needed testfiles // equal to {pattern: 'test/unit/*.spec.js', watched: true, served: true, included: true} 'test/unit/*.spec.js', // this file gets served but will be ignored by the watcher // note if html2js preprocessor is active, reference as `window.__html__['compiled/index.html']` {pattern: 'compiled/index.html', watched: false}, // this file only gets watched and is otherwise ignored {pattern: 'app/index.html', included: false, served: false}, // this file will be served on demand from disk and will be ignored by the watcher {pattern: 'compiled/app.js.map', included: false, served: true, watched: false, nocache: true} ], ``` -------------------------------- ### Configure .codio file for Karma Source: https://karma-runner.github.io/6.4/plus/codio.html Configuration for the Codio project's .codio file. It defines the Run and Preview buttons: 'Karma Start' runs 'karma start --no-browsers', 'Karam Run' runs 'karma run', and 'Karma Preview' opens 'http://{{domain}}:8080'. Note the typo 'Karam Run' in the source. The port can be changed, but must match the port in karma.conf.js. ```json { // Configure your Run and Preview buttons here. // Run button configuration "commands": { "Karma Start": "karma start --no-browsers" "Karam Run": "karma run" }, // Preview button configuration "preview": { "Karma Preview": "http://{{domain}}:8080" } } ``` -------------------------------- ### Install a Karma plugin with npm Source: https://karma-runner.github.io/6.4/config/plugins.html Install a Karma plugin from npm and save it as a dev dependency. Replace with the actual plugin name. ```bash npm install karma- --save-dev ``` -------------------------------- ### Install Karma and plugins locally Source: https://karma-runner.github.io/6.4/intro/installation.html Installs Karma and the plugins karma-jasmine, karma-chrome-launcher, and jasmine-core as devDependencies in the current project directory. ```bash # Install Karma: $ npm install karma --save-dev # Install plugins that your project needs: $ npm install karma-jasmine karma-chrome-launcher jasmine-core --save-dev ``` -------------------------------- ### Contradictory preprocessor order example Source: https://karma-runner.github.io/6.4/config/preprocessors.html Shows a config with contradictory orders; Karma arbitrarily picks one list to prioritize. ```javascript preprocessors: { '*.js': ['a', 'b'], 'a.*': ['b', 'a'] } ``` -------------------------------- ### Install latest Karma Source: https://karma-runner.github.io/6.4/about/migration.html Run this command in your project directory to install the latest version of Karma and update package.json. ```bash cd npm install karma --save-dev ``` -------------------------------- ### Simple QUnit test example Source: https://karma-runner.github.io/6.4/plus/emberjs.html A simple QUnit test example that asserts equality. This test is added to the test files and run with Karma. ```javascript test('one should equal one', function() { equal(1, 1, 'error: one did not equal one'); }); ``` -------------------------------- ### runner.run(options, [callback=process.exit]) Source: https://karma-runner.github.io/6.4/dev/public-api.html Documentation for the runner.run method, including usage examples and event handling. ```APIDOC ## runner.run(options, [callback=process.exit]) ### Description Runs Karma tests, equivalent to the `karma run` command. Returns an EventEmitter that emits a `progress` event with reporter output. ### Method runner.run ### Parameters - **options** (Object) - Required - Configuration options, typically a parsed Karma config object or an object with a `port` property. - **callback** (Function) - Optional - Callback function that receives the exit code as the first argument and an optional error code as the second argument. ### Returns - **EventEmitter** - Emits a `progress` event with a `Buffer` of reporter output. ### Usage Example (Deprecated) ```javascript var runner = require('karma').runner runner.run({port: 9876}, function(exitCode) { console.log('Karma has exited with ' + exitCode) process.exit(exitCode) }) ``` ### Usage Example (New Behavior) ```javascript const karma = require('karma') karma.config.parseConfig( null, { port: 9876 }, { promiseConfig: true, throwErrors: true } ).then( (karmaConfig) => { karma.runner.run(karmaConfig, function doneCallback(exitCode, possibleErrorCode) { console.log('Karma has exited with ' + exitCode) process.exit(exitCode) }) }, (rejectReason) => { /* respond to the rejection reason error */ } ); ``` ### Events - **progress** - Emitted with a `Buffer` of reporter output. Example: ```javascript runner.run({port: 9876}).on('progress', function(data) { process.stdout.write(data) }) ``` ``` -------------------------------- ### Start Karma without browsers Source: https://karma-runner.github.io/6.4/plus/cloud9.html Starts Karma without launching any browsers, allowing manual capture from a local browser. ```bash # Start Karma without browsers: $ karma start --no-browsers ``` -------------------------------- ### Install Karma with NPM Source: https://karma-runner.github.io/6.4/about/versioning.html Adds Karma as a development dependency using npm. ```bash $ npm --save-dev install karma ``` -------------------------------- ### Karma Server Usage Source: https://karma-runner.github.io/6.4/about/changelog.html Shows the canonical way to start a Karma server after the removal of deprecated static methods. Use this instead of the removed `require('karma').server.start()` and `require('karma').Server.start()` variants. ```javascript const { Server } = require('karma'); const server = new Server(); server.start(); ``` -------------------------------- ### Event: 'run_start' Source: https://karma-runner.github.io/6.4/dev/public-api.html Event emitted when a test run starts. ```APIDOC ## Event: 'run_start' ### Description Emitted when a test run starts. ### Arguments - **browsers** (array) - A collection of browser instances on which tests are executed. ``` -------------------------------- ### Configure Travis with Firefox (Trusty and below) Source: https://karma-runner.github.io/6.4/plus/travis.html Update .travis.yml to set up a virtual screen for Firefox on Trusty and below. This exports DISPLAY and starts xvfb. ```yaml language: node_js node_js: - "4" before_script: - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start ``` -------------------------------- ### Install Karma with Yarn Source: https://karma-runner.github.io/6.4/about/versioning.html Adds Karma as a development dependency using yarn. ```bash $ yarn add --dev karma ``` -------------------------------- ### Upgrade to constructor-based server API (before) Source: https://karma-runner.github.io/6.4/about/changelog.html Old way to start the Karma server before version 0.13.0. The public API changed to a constructor form, so this code must be updated. ```javascript var server = require(‘karma’).server server.start(config, done) ``` -------------------------------- ### Run Karma locally Source: https://karma-runner.github.io/6.4/intro/installation.html Runs Karma using the locally installed binary in node_modules. ```bash # Run Karma: $ ./node_modules/karma/bin/karma start ``` -------------------------------- ### stopper.stop(options, [callback=process.exit]) Source: https://karma-runner.github.io/6.4/dev/public-api.html Documentation for the stopper.stop method, including usage examples and callback behavior. ```APIDOC ## stopper.stop(options, [callback=process.exit]) ### Description Signals a running Karma server to stop, equivalent to the `karma stop` command. ### Method stopper.stop ### Parameters - **options** (Object) - Required - Configuration options, typically a parsed Karma config object or an object with a `port` property. - **callback** (Function) - Optional - Callback function that receives the exit code as the first argument and an optional error code as the second argument. ### Usage Example (Deprecated) ```javascript var stopper = require('karma').stopper stopper.stop({port: 9876}, function(exitCode) { if (exitCode === 0) { console.log('Server stop as initiated') } process.exit(exitCode) }) ``` ### Usage Example (New Behavior) ```javascript const karma = require('karma') karma.config.parseConfig( null, { port: 9876 }, { promiseConfig: true, throwErrors: true } ).then( (karmaConfig) => { karma.stopper.stop(karmaConfig, function doneCallback(exitCode, possibleErrorCode) { if (exitCode === 0) { console.log('Server stop as initiated') } process.exit(exitCode) }) }, (rejectReason) => { /* respond to the rejection reason error */ } ); ``` ``` -------------------------------- ### mime configuration example Source: https://karma-runner.github.io/6.4/config/configuration-file.html Redefines default file extension to MIME-type mappings. Set property name to the required MIME type and provide an array of extensions (without dots) as its value. ```javascript mime: { 'text/x-typescript': ['ts','tsx'] 'text/plain' : ['mytxt'] } ``` -------------------------------- ### Define custom launchers Source: https://karma-runner.github.io/6.4/config/browsers.html Define custom launchers with base browser and flags. This example shows a Chrome launcher without security and a SauceLabs launcher for Windows. ```javascript customLaunchers: { chrome_without_security: { base: 'Chrome', flags: ['--disable-web-security'] }, sauce_chrome_win: { base: 'SauceLabs', browserName: 'chrome', platform: 'windows' } } ``` -------------------------------- ### proxies configuration example Source: https://karma-runner.github.io/6.4/config/configuration-file.html Defines a map of path-proxy pairs. The proxy can be a target URL/path string or an object with 'target' and 'changeOrigin' options. The 'changeOrigin' option overrides the Host header using the target's host, defaulting to false. ```javascript proxies: { '/static': 'http://gstatic.com', '/web': 'http://localhost:9000', '/img/': '/base/test/images/', '/proxyfied': { 'target': 'http://myserver.localhost', 'changeOrigin': true } }, ``` -------------------------------- ### Remove global karma package Source: https://karma-runner.github.io/6.4/about/migration.html If you have the karma package installed globally, remove it before installing the CLI. ```bash npm remove -g karma ``` -------------------------------- ### Configure coffeePreprocessor options Source: https://karma-runner.github.io/6.4/config/preprocessors.html Shows how to set options for the 'coffee' preprocessor, such as 'bare: false'. ```javascript coffeePreprocessor: { options: { bare: false } } ``` -------------------------------- ### hello-plugin.js - Declare a framework plugin Source: https://karma-runner.github.io/6.4/dev/plugins.html Defines a factory function that logs 'Hello, world!' when instantiated. The plugin exports a DI token 'framework:hello' mapped to the factory, so Karma instantiates it when the plugin is activated. ```javascript // hello-plugin.js // A factory function for our plugin, it will be called, when Karma needs to // instantiate a plugin. Normally it should return an instance of the service // conforming to the API requirements of the plugin type (more on that below), // but for our simple example we don't need any service and just print // a message when function is called. function helloFrameworkFactory() { console.log('Hello, world!') } module.exports = { // Declare the plugin, so Karma knows that it exists. // 'factory' tells Karma that it should call `helloFrameworkFactory` // function and use whatever it returns as a service for the DI token // `framework:hello`. 'framework:hello': ['factory', helloFrameworkFactory] }; ``` ```javascript // karma.conf.js module.exports = (config) => { config.set({ plugins: [ require('./hello-plugin') ], // Activate our plugin by specifying its unique name in the // corresponding configuration key. frameworks: ['hello'] }) } ``` -------------------------------- ### Example commit message Source: https://karma-runner.github.io/6.4/dev/git-commit-msg.html Example of a properly formatted commit message with a fix type, scope, subject, body, and footer referencing an issue. ```text fix(middleware): ensure Range headers adhere more closely to RFC 2616 Add one new dependency, use `range-parser` (Express dependency) to compute range. It is more well-tested in the wild. Fixes #2310 ``` -------------------------------- ### Ember bootstrap file to delay Karma test start Source: https://karma-runner.github.io/6.4/plus/emberjs.html Bootstrap file to prevent Karma from starting tests until the Ember application has finished initialization. It overrides __karma__.loaded, sets up testing helpers, and uses an initializer to start Karma only once, guarding against repeated calls due to Ember.reset() in test teardown. ```javascript __karma__.loaded = function() {}; App.setupForTesting(); App.injectTestHelpers(); //this gate/check is required given that standard practice in Ember tests to is to call //Ember.reset() in the afterEach/tearDown for each test. Doing so, causes the application //to 're-initialize', resulting in repeated calls to the initialize function below var karma_started = false; App.initializer({ name: "run tests", initialize: function(container, application) { if (!karma_started) { karma_started = true; __karma__.start(); } } }); ``` -------------------------------- ### New Karma Server constructor with parseConfig Source: https://karma-runner.github.io/6.4/dev/public-api.html New recommended way to create a Karma server. Uses `karma.config.parseConfig` with `promiseConfig: true` and `throwErrors: true`, then constructs a `Server` with the parsed config. The callback logs the exit code and calls `process.exit`. ```javascript const karma = require('karma') const parseConfig = karma.config.parseConfig const Server = karma.Server parseConfig( null, { port: 9876 }, { promiseConfig: true, throwErrors: true } ).then( (karmaConfig) => { const server = new Server(karmaConfig, function doneCallback(exitCode) { console.log('Karma has exited with ' + exitCode) process.exit(exitCode) }) }, (rejectReason) => { /* respond to the rejection reason error */ } ); ``` -------------------------------- ### Generate Karma config file with karma init Source: https://karma-runner.github.io/6.4/intro/configuration.html Run `karma init my.conf.js` to interactively generate a configuration file. The command prompts for testing framework, Require.js usage, browser capture, source/test file patterns, exclusions, and file watching. The output shows the generated config file path. ```bash $ karma init my.conf.js Which testing framework do you want to use? Press tab to list possible options. Enter to move to the next question. > jasmine Do you want to use Require.js? This will add Require.js plugin. Press tab to list possible options. Enter to move to the next question. > no Do you want to capture a browser automatically? Press tab to list possible options. Enter empty string to move to the next question. > Chrome > Firefox > What is the location of your source and test files? You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js". Press Enter to move to the next question. > *.js > test/**/*.js > Should any of the files included by the previous patterns be excluded? You can use glob patterns, eg. "**/*.swp". Press Enter to move to the next question. > Do you want Karma to watch all the files and run the tests on change? Press tab to list possible options. > yes Config file generated at "/Users/vojta/Code/karma/my.conf.js". ``` -------------------------------- ### proxyReq example: overwriting HTTP header Source: https://karma-runner.github.io/6.4/config/configuration-file.html Use this configuration to modify the proxy request before it is sent. The example sets the 'Referer' header to 'https://www.example.com/'. This function is called when requesting through the proxy. ```javascript proxyReq: function(proxyReq, req, res, options) { proxyReq.setHeader('Referer', 'https://www.example.com/'); } ``` -------------------------------- ### Manual requirejs loading with knockout.js Source: https://karma-runner.github.io/6.4/plus/requirejs.html Alternative configuration to load requirejs and adapter manually, allowing custom script order. ```javascript config.set({ frameworks: ['jasmine'], files: [ 'knockout.js', 'node_modules/requirejs/require.js', 'node_modules/karma-requirejs/lib/adapter.js', {pattern: 'lib/**/*.js', included: false}, {pattern: 'src/**/*.js', included: false}, {pattern: 'test/**/*Spec.js', included: false}, 'test/test-main.js' ], ``` -------------------------------- ### Set up test command in package.json Source: https://karma-runner.github.io/6.4/plus/travis.html Add Karma as a devDependency and define the test script to run Karma with PhantomJS. Travis runs npm test to trigger your tests. ```json // ...snip... "devDependencies": { "karma": "~0.12" }, // ...snip... "scripts": { "test": "karma start --single-run --browsers PhantomJS" } // ...snip... ``` -------------------------------- ### karma.Server constructor Source: https://karma-runner.github.io/6.4/dev/public-api.html Constructor for the Karma Server class. It initializes a new server instance with the provided configuration and an optional exit callback. ```APIDOC ## karma.Server(options, [callback=process.exit]) ### Description Creates a new Karma server instance. The constructor accepts a configuration object and an optional callback that is invoked when the server exits. ### Method constructor ### Parameters - **options** (object) - Required - Karma configuration object. - **callback** (function) - Optional - Callback function that receives the exit code. ### Returns - **Server** - A new Server instance. ### Usage ``` var Server = require('karma').Server var karmaConfig = {port: 9876} var server = new Server(karmaConfig, function(exitCode) { console.log('Karma has exited with ' + exitCode) process.exit(exitCode) }) ``` ### New Behavior ``` const karma = require('karma') const parseConfig = karma.config.parseConfig const Server = karma.Server parseConfig( null, { port: 9876 }, { promiseConfig: true, throwErrors: true } ).then( (karmaConfig) => { const server = new Server(karmaConfig, function doneCallback(exitCode) { console.log('Karma has exited with ' + exitCode) process.exit(exitCode) }) }, (rejectReason) => { /* respond to the rejection reason error */ } ); ``` ``` -------------------------------- ### Event: 'browser_start' Source: https://karma-runner.github.io/6.4/dev/public-api.html Event emitted when a test run is beginning in a browser. ```APIDOC ## Event: 'browser_start' ### Description Emitted when a test run is beginning in a browser. ### Arguments - **browser** (object) - The browser instance. - **info** (object) - Details about the run. ``` -------------------------------- ### Load image assets with glob pattern Source: https://karma-runner.github.io/6.4/config/files.html Configure files to serve image assets from a glob pattern. Watched and included are not necessary for images, but served must be true. Images are accessed at http://localhost:[PORT]/base/test/images/[MY IMAGE].jpg. ```javascript files: [ {pattern: 'test/images/*.jpg', watched: false, included: false, served: true, nocache: false} ], ``` -------------------------------- ### Configure Travis with Node.js Source: https://karma-runner.github.io/6.4/plus/travis.html Create a .travis.yml file in your project root with this YAML content to set up Travis CI for Node.js. ```yaml language: node_js node_js: - "4" ``` -------------------------------- ### Add Karma plugins to package.json devDependencies Source: https://karma-runner.github.io/6.4/config/plugins.html Add Karma plugins as project dependencies in package.json. The recommended way to install plugins is to add them as devDependencies. ```json { "devDependencies": { "karma": "~0.10", "karma-mocha": "~0.0.1", "karma-growl-reporter": "~0.0.1", "karma-firefox-launcher": "~0.0.1" } } ```