Catalog / Karma Testing Cheatsheet
Karma Testing Cheatsheet
A comprehensive cheat sheet for Karma, the test runner for JavaScript. This guide covers configuration, common commands, debugging techniques, and best practices to streamline your testing workflow.
Karma Configuration
Basic Configuration File (karma.conf.js)
The |
|
Key Configuration Options
|
An array of testing frameworks to use (e.g., ‘jasmine’, ‘mocha’, ‘qunit’). |
|
An array of file patterns to load. Order matters; dependencies should be listed first. |
|
An array of file patterns to exclude from loading. |
|
An array of reporters to use (e.g., ‘progress’, ‘dots’, ‘coverage’). |
|
The port Karma will listen on. |
|
An array of browsers to launch for testing (e.g., ‘Chrome’, ‘Firefox’, ‘Safari’). |
|
If true, Karma will watch files for changes and rerun tests automatically. |
|
If true, Karma will run tests once and exit. |
Preprocessors
Preprocessors apply transformations to files before they are served to the browser. Common use cases include transpiling code (e.g., Babel for ES6) and generating coverage reports. |
|
Running Karma Tests
Basic Commands
|
Starts the Karma test runner using the configuration file (karma.conf.js). |
|
Triggers a test run without restarting the Karma server. Requires the server to be already running. |
|
Helps create a karma.conf.js file in the current directory. |
Command-Line Options
You can override configuration options from the command line using |
|
|
|
Example Commands
Run tests in Chrome once and exit: |
Run tests and keep watching for changes: |
Debugging Karma Tests
Debugging Techniques
Karma provides several ways to debug your tests, including using browser developer tools and the |
Using Browser Developer Tools
|
Launch your tests using Karma, then open the developer tools in the browser (e.g., Chrome DevTools, Firefox Developer Tools). |
|
Insert |
|
Use the console or debugger to inspect variables and step through your code. |
browserConsoleLog
The |
|
Advanced Karma Features
Custom Launchers
You can configure custom browser launchers to run tests in specific environments, such as headless Chrome or custom browser configurations. |
|
Plugins
Karma supports a wide range of plugins to extend its functionality, including reporters, preprocessors, and frameworks. Install plugins using npm and configure them in your |
Reporters
|
Displays a progress bar and test results in the console. |
|
Displays test results using dots in the console. |
|
Generates code coverage reports. |
|
Generates JUnit-style XML reports. |