0
# Programmatic API
1
2
Core programmatic interfaces for integrating Karma into build tools, CI/CD systems, and custom test runners. Provides full control over server lifecycle, test execution, and browser management.
3
4
## Capabilities
5
6
### Server Class
7
8
Main Karma server class that manages the HTTP server, file watching, and browser coordination.
9
10
```javascript { .api }
11
/**
12
* Karma server class for managing test environment
13
* @extends EventEmitter
14
*/
15
class Server extends EventEmitter {
16
/**
17
* Create new Karma server instance. Constructor automatically starts the server.
18
* @param cliOptionsOrConfig - Configuration object or CLI options
19
* @param done - Optional callback function (defaults to process.exit)
20
*/
21
constructor(cliOptionsOrConfig: Config | Object, done?: Function);
22
23
/**
24
* Stop the Karma server gracefully
25
* @returns Promise that resolves when server is stopped
26
*/
27
stop(): Promise<void>;
28
29
/**
30
* Refresh all watched files
31
* @returns Promise<void>
32
*/
33
refreshFiles(): Promise<void>;
34
35
/**
36
* Refresh specific file by path
37
* @param path - File path to refresh
38
* @returns Promise<void>
39
*/
40
refreshFile(path: string): Promise<void>;
41
42
/**
43
* Get dependency injection token value
44
* @param token - Token name to retrieve
45
* @returns Any value associated with the token
46
*/
47
get(token: string): any;
48
49
/**
50
* Emit exit event asynchronously
51
* @param code - Exit code
52
* @returns Promise that resolves when all exit listeners complete
53
*/
54
emitExitAsync(code: number): Promise<void>;
55
}
56
```
57
58
**Usage Examples:**
59
60
```javascript
61
const karma = require('karma');
62
63
// Create server with configuration (automatically starts)
64
const server = new karma.Server({
65
configFile: './karma.conf.js',
66
singleRun: true,
67
browsers: ['Chrome']
68
}, (exitCode) => {
69
console.log('Tests completed with exit code:', exitCode);
70
});
71
72
// Listen to server events
73
server.on('listening', () => {
74
console.log('Karma server started');
75
});
76
77
server.on('browser_register', (browser) => {
78
console.log('Browser connected:', browser.name);
79
});
80
81
server.on('run_complete', (browsers, results) => {
82
console.log('Test run complete:', results);
83
});
84
85
// Server starts automatically from constructor
86
// Use server.stop() to stop gracefully
87
```
88
89
### Runner Module
90
91
Execute tests on a running Karma server, typically used for triggering test runs from external tools.
92
93
```javascript { .api }
94
/**
95
* Execute tests on running Karma server
96
* @param cliOptionsOrConfig - Configuration object or CLI options
97
* @param done - Callback function with exit code
98
* @returns EventEmitter for progress events
99
*/
100
function run(cliOptionsOrConfig: Config | Object, done?: Function): EventEmitter;
101
```
102
103
**Usage Examples:**
104
105
```javascript
106
const karma = require('karma');
107
108
// Run tests and get progress updates
109
const runner = karma.runner.run({
110
port: 9876,
111
hostname: 'localhost'
112
}, (exitCode) => {
113
console.log('Test run finished with code:', exitCode);
114
});
115
116
// Listen to progress events
117
runner.on('progress', (data) => {
118
console.log('Test progress:', data);
119
});
120
121
// Alternative with async/await
122
const config = karma.config.parseConfig('./karma.conf.js', {});
123
const runResult = karma.runner.run(config);
124
```
125
126
### Stopper Module
127
128
Stop a running Karma server programmatically.
129
130
```javascript { .api }
131
/**
132
* Stop running Karma server
133
* @param cliOptionsOrConfig - Configuration object or CLI options
134
* @param done - Callback function with exit code
135
*/
136
function stop(cliOptionsOrConfig: Config | Object, done?: Function): void;
137
```
138
139
**Usage Examples:**
140
141
```javascript
142
const karma = require('karma');
143
144
// Stop server with callback
145
karma.stopper.stop({
146
port: 9876,
147
hostname: 'localhost'
148
}, (exitCode) => {
149
if (exitCode === 0) {
150
console.log('Server stopped successfully');
151
} else {
152
console.error('Failed to stop server');
153
}
154
});
155
156
// Stop with configuration
157
const config = karma.config.parseConfig('./karma.conf.js');
158
karma.stopper.stop(config);
159
```
160
161
### Launcher Module
162
163
Manage browser instances for testing, including launching, monitoring, and cleanup.
164
165
```javascript { .api }
166
/**
167
* Browser launcher class for managing browser instances
168
*/
169
class Launcher {
170
/**
171
* Create launcher instance
172
* @param server - Karma server instance
173
* @param emitter - Event emitter
174
* @param injector - Dependency injector
175
*/
176
constructor(server: Server, emitter: EventEmitter, injector: any);
177
178
/**
179
* Launch browsers by name
180
* @param names - Array of browser names to launch
181
* @param concurrency - Maximum concurrent browsers
182
* @returns Promise that resolves when browsers are launched
183
*/
184
launch(names: string[], concurrency: number): Promise<void>;
185
186
/**
187
* Create single browser launcher function
188
* @param protocol - Server protocol
189
* @param hostname - Server hostname
190
* @param port - Server port
191
* @param urlRoot - URL root path
192
* @param upstreamProxy - Upstream proxy config
193
* @param processKillTimeout - Process kill timeout
194
* @returns Browser instance
195
*/
196
launchSingle(
197
protocol: string,
198
hostname: string,
199
port: number,
200
urlRoot: string,
201
upstreamProxy: any,
202
processKillTimeout: number
203
): Browser;
204
205
/**
206
* Kill specific browser by ID
207
* @param id - Browser ID
208
* @returns True if browser was found and killed
209
*/
210
kill(id: string): boolean;
211
212
/**
213
* Restart browser by ID
214
* @param id - Browser ID
215
* @returns True if browser was found and restarted
216
*/
217
restart(id: string): boolean;
218
219
/**
220
* Kill all launched browsers
221
* @returns Promise that resolves when all browsers are killed
222
*/
223
killAll(): Promise<void>;
224
225
/**
226
* Check if all browsers are captured
227
* @returns True if all browsers captured
228
*/
229
areAllCaptured(): boolean;
230
231
/**
232
* Mark browser as captured
233
* @param id - Browser ID
234
*/
235
markCaptured(id: string): void;
236
237
/**
238
* Get all browser instances
239
* @returns Array of browser instances
240
*/
241
getBrowsers(): Browser[];
242
243
/**
244
* Get number of captured browsers
245
* @returns Number of captured browsers
246
*/
247
getCapturedBrowsers(): number;
248
}
249
```
250
251
### Constants
252
253
Access to all Karma constants including version, defaults, and log levels.
254
255
```javascript { .api }
256
interface Constants {
257
VERSION: string; // Karma version
258
DEFAULT_PORT: number; // Default port (9876)
259
DEFAULT_HOSTNAME: string; // Default hostname ('localhost')
260
DEFAULT_LISTEN_ADDR: string; // Default listen address ('0.0.0.0')
261
262
// Log levels
263
LOG_DISABLE: string; // 'OFF'
264
LOG_ERROR: string; // 'ERROR'
265
LOG_WARN: string; // 'WARN'
266
LOG_INFO: string; // 'INFO'
267
LOG_DEBUG: string; // 'DEBUG'
268
LOG_LOG: string; // 'LOG'
269
LOG_PRIORITIES: string[]; // Log levels in priority order
270
271
// Patterns
272
COLOR_PATTERN: string; // Default color pattern
273
NO_COLOR_PATTERN: string; // Default no-color pattern
274
CONSOLE_APPENDER: Object; // Default console appender
275
EXIT_CODE: string; // Internal exit code marker
276
}
277
```
278
279
**Usage Examples:**
280
281
```javascript
282
const karma = require('karma');
283
284
console.log('Karma version:', karma.constants.VERSION);
285
console.log('Default port:', karma.constants.DEFAULT_PORT);
286
287
// Use log levels
288
const config = {
289
logLevel: karma.constants.LOG_DEBUG,
290
port: karma.constants.DEFAULT_PORT
291
};
292
```
293
294
## Event System
295
296
Karma uses EventEmitter extensively for real-time updates during test execution.
297
298
### Server Events
299
300
```javascript { .api }
301
// Server lifecycle events
302
'listening' // Server started listening
303
'browser_register' // Browser connected (browser)
304
'browser_start' // Browser started (browser)
305
'browser_complete' // Browser finished (browser, result)
306
'browser_error' // Browser error (browser, error)
307
'run_start' // Test run started (browsers)
308
'run_complete' // Test run finished (browsers, results)
309
'file_list_modified' // File list changed
310
311
// Progress events
312
'spec_complete' // Individual test completed (browser, result)
313
'coverage_complete' // Coverage data available (browser, coverage)
314
```
315
316
### Runner Events
317
318
```javascript { .api }
319
// Runner progress events
320
'progress' // Test execution progress (data)
321
```
322
323
**Usage Examples:**
324
325
```javascript
326
const server = new karma.Server(config);
327
328
server.on('listening', () => {
329
console.log('Karma server listening on port', server.get('config.port'));
330
});
331
332
server.on('run_complete', (browsers, results) => {
333
console.log('Tests completed:');
334
console.log(' Success:', results.success);
335
console.log(' Failed:', results.failed);
336
console.log(' Total time:', results.totalTime + 'ms');
337
});
338
339
server.on('browser_error', (browser, error) => {
340
console.error('Browser error in', browser.name, ':', error);
341
});
342
```