0
# Karma Test Runner
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: karma
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install karma --save-dev`
10
11
## Core Imports
12
13
```javascript
14
const karma = require('karma');
15
const { Server, runner, stopper, launcher, config, constants } = require('karma');
16
```
17
18
ES6 modules:
19
20
```javascript
21
import karma from 'karma';
22
import { Server, runner, stopper, launcher, config, constants } from 'karma';
23
```
24
25
## Basic Usage
26
27
```javascript
28
const karma = require('karma');
29
30
// Parse configuration
31
const config = karma.config.parseConfig('./karma.conf.js', {
32
singleRun: true,
33
browsers: ['Chrome']
34
});
35
36
// Create and start server
37
const server = new karma.Server(config, (exitCode) => {
38
console.log('Karma has exited with', exitCode);
39
process.exit(exitCode);
40
});
41
42
server.start();
43
```
44
45
## Architecture
46
47
Karma's architecture consists of several key components:
48
49
- **Test Server**: HTTP server that serves test files and coordinates test execution
50
- **Browser Management**: Launches and manages multiple browser instances for testing
51
- **File System**: Watches source files and test files for changes, with preprocessing support
52
- **Plugin System**: Extensible architecture for browsers, frameworks, reporters, and preprocessors
53
- **CLI Interface**: Command-line tools for configuration, running tests, and server management
54
- **Configuration System**: Flexible configuration with JavaScript, TypeScript, and JSON support
55
56
## Capabilities
57
58
### Programmatic API
59
60
Core programmatic interfaces for server management, test execution, and browser control. Ideal for build tools and custom test runners.
61
62
```javascript { .api }
63
// Main server class for managing test environment
64
class Server extends EventEmitter {
65
constructor(cliOptionsOrConfig: Config | Object, done?: Function); // Automatically starts server
66
stop(): Promise<void>;
67
refreshFiles(): Promise<void>;
68
refreshFile(path: string): Promise<void>;
69
get(token: string): any;
70
emitExitAsync(code: number): Promise<void>;
71
}
72
73
// Test runner functions
74
function runner.run(cliOptionsOrConfig: Config | Object, done?: Function): EventEmitter;
75
function stopper.stop(cliOptionsOrConfig: Config | Object, done?: Function): void;
76
77
// Launcher for managing browser instances
78
class Launcher {
79
constructor(server: Server, emitter: EventEmitter, injector: any);
80
launch(browsers: string[], concurrency: number): Promise<void>;
81
launchSingle(protocol: string, hostname: string, port: number, urlRoot: string, upstreamProxy: any, processKillTimeout: number): Browser;
82
kill(id: string): boolean;
83
restart(id: string): boolean;
84
killAll(): Promise<void>;
85
areAllCaptured(): boolean;
86
markCaptured(id: string): void;
87
}
88
89
// Constants and version information
90
const constants: {
91
VERSION: string;
92
DEFAULT_PORT: number;
93
DEFAULT_HOSTNAME: string;
94
DEFAULT_LISTEN_ADDR: string;
95
LOG_DISABLE: string;
96
LOG_ERROR: string;
97
LOG_WARN: string;
98
LOG_INFO: string;
99
LOG_DEBUG: string;
100
LOG_LOG: string;
101
LOG_PRIORITIES: string[];
102
COLOR_PATTERN: string;
103
NO_COLOR_PATTERN: string;
104
CONSOLE_APPENDER: object;
105
EXIT_CODE: string;
106
};
107
```
108
109
[Programmatic API](./programmatic-api.md)
110
111
### CLI Interface
112
113
Command-line interface for interactive development and CI/CD integration. Supports project initialization, test execution, and server management.
114
115
```javascript { .api }
116
// Available CLI commands
117
karma init [configFile] // Initialize configuration file
118
karma start [configFile] // Start server and/or run tests
119
karma run [configFile] // Trigger test run on existing server
120
karma stop [configFile] // Stop running server
121
karma completion // Generate shell completion
122
```
123
124
[CLI Interface](./cli-interface.md)
125
126
### Configuration System
127
128
Comprehensive configuration system supporting multiple formats and extensive customization options.
129
130
```javascript { .api }
131
function config.parseConfig(
132
configFilePath?: string,
133
cliOptions?: Object,
134
parseOptions?: {
135
promiseConfig?: boolean;
136
throwErrors?: boolean;
137
}
138
): Config | Promise<Config>;
139
140
// Configuration pattern classes
141
class Pattern {
142
constructor(pattern: string, served?: boolean, included?: boolean, watched?: boolean, nocache?: boolean, type?: string, isBinary?: boolean, integrity?: string);
143
pattern: string;
144
served: boolean;
145
included: boolean;
146
watched: boolean;
147
nocache: boolean;
148
weight: number;
149
type?: string;
150
isBinary?: boolean;
151
integrity?: string;
152
compare(other: Pattern): number;
153
}
154
155
class UrlPattern extends Pattern {
156
constructor(url: string, type?: string, integrity?: string);
157
}
158
159
function createPatternObject(pattern: string | object): Pattern | UrlPattern;
160
161
class Config {
162
// Core configuration properties
163
port: number;
164
hostname: string;
165
basePath: string;
166
frameworks: string[];
167
files: (string | Pattern)[];
168
exclude: string[];
169
browsers: string[];
170
reporters: string[];
171
// ... extensive configuration options
172
}
173
```
174
175
[Configuration](./configuration.md)
176
177
### Plugin System
178
179
Extensible plugin architecture supporting custom browsers, reporters, preprocessors, and frameworks.
180
181
```javascript { .api }
182
// Plugin registration and resolution
183
function plugin.resolve(plugins: string[], emitter: EventEmitter): any[];
184
function plugin.createInstantiatePlugin(injector: any): Function;
185
186
// Built-in plugin categories
187
interface PluginTypes {
188
'launcher': BrowserLauncher; // Browser launchers
189
'reporter': Reporter; // Test result reporters
190
'preprocessor': Preprocessor; // File preprocessors
191
'framework': Framework; // Testing frameworks
192
'middleware': Middleware; // Custom middleware
193
}
194
```
195
196
[Plugin System](./plugin-system.md)
197
198
### Constants and Utilities
199
200
Core constants, version information, and utility functions for configuration and integration.
201
202
```javascript { .api }
203
// Version and default configuration constants
204
const VERSION: string;
205
const DEFAULT_PORT: number;
206
const DEFAULT_HOSTNAME: string;
207
const DEFAULT_LISTEN_ADDR: string;
208
209
// Logging level constants
210
const LOG_DISABLE: string;
211
const LOG_ERROR: string;
212
const LOG_WARN: string;
213
const LOG_INFO: string;
214
const LOG_DEBUG: string;
215
const LOG_LOG: string;
216
const LOG_PRIORITIES: string[];
217
218
// Logger configuration
219
const COLOR_PATTERN: string;
220
const NO_COLOR_PATTERN: string;
221
const CONSOLE_APPENDER: {
222
type: string;
223
layout: {
224
type: string;
225
pattern: string;
226
};
227
};
228
229
// Internal constants
230
const EXIT_CODE: string;
231
```
232
233
## Types
234
235
```javascript { .api }
236
interface Config {
237
// Server configuration
238
port: number;
239
hostname: string;
240
listenAddress: string;
241
urlRoot: string;
242
243
// File configuration
244
basePath: string;
245
files: (string | Pattern)[];
246
exclude: string[];
247
preprocessors: { [key: string]: string[] };
248
249
// Browser configuration
250
browsers: string[];
251
customLaunchers: { [key: string]: any };
252
browserDisconnectTimeout: number;
253
browserDisconnectTolerance: number;
254
browserNoActivityTimeout: number;
255
captureTimeout: number;
256
257
// Test execution
258
singleRun: boolean;
259
autoWatch: boolean;
260
watchOptions: { [key: string]: any };
261
262
// Reporting
263
reporters: string[];
264
colors: boolean;
265
logLevel: string;
266
267
// Framework and plugins
268
frameworks: string[];
269
plugins: string[];
270
271
// Advanced options
272
client: { [key: string]: any };
273
middleware: string[];
274
proxies: { [key: string]: string };
275
upstreamProxy: { [key: string]: any };
276
retryLimit: number;
277
detached: boolean;
278
crossOriginAttribute: boolean;
279
}
280
281
interface Pattern {
282
pattern: string;
283
served: boolean;
284
included: boolean;
285
watched: boolean;
286
nocache: boolean;
287
weight: number;
288
type?: string;
289
isBinary?: boolean;
290
integrity?: string;
291
compare(other: Pattern): number;
292
}
293
294
interface UrlPattern extends Pattern {
295
// Inherits all Pattern properties but with specific defaults for URLs
296
}
297
298
interface File {
299
path: string; // Served path (may be processed)
300
originalPath: string; // Original absolute path
301
contentPath: string; // Content storage path
302
mtime: Date; // Last modified time
303
isUrl: boolean; // Is external URL
304
doNotCache: boolean; // Disable caching
305
type?: string; // MIME type
306
isBinary?: boolean; // Binary file flag
307
integrity?: string; // Subresource integrity hash
308
encodings: { [key: string]: Buffer }; // Encoded content cache
309
}
310
311
interface Browser {
312
id: string; // Unique browser ID
313
fullName: string; // Full browser name with version
314
name: string; // Short browser name
315
state: string; // Current browser state
316
lastResult: BrowserResult; // Last test execution result
317
disconnectsCount: number; // Number of disconnections
318
activeSockets: Socket[]; // Active socket connections
319
noActivityTimeout: number; // No activity timeout
320
singleRun: boolean; // Single run mode
321
322
// Methods
323
init(): void;
324
setState(state: string): void;
325
disconnect(reason?: string): void;
326
reconnect(newSocket: Socket): void;
327
execute(config: any): void;
328
refresh(): Promise<void>;
329
serialize(): object;
330
}
331
332
interface BrowserResult {
333
id: string;
334
fullName: string;
335
name: string;
336
state: string;
337
lastResult: {
338
success: number;
339
failed: number;
340
skipped: number;
341
total: number;
342
totalTime: number;
343
netTime: number;
344
error: boolean;
345
disconnected: boolean;
346
};
347
}
348
```