0
# Configuration
1
2
Karma's comprehensive configuration system supports multiple file formats and extensive customization options. Configuration files define test execution behavior, file patterns, browser selection, and plugin configuration.
3
4
## Capabilities
5
6
### parseConfig Function
7
8
Parse and normalize Karma configuration from files and CLI options.
9
10
```javascript { .api }
11
/**
12
* Parse Karma configuration from file and CLI options
13
* @param configFilePath - Path to configuration file (optional)
14
* @param cliOptions - CLI option overrides (optional)
15
* @param parseOptions - Parsing behavior options (optional)
16
* @returns Configuration object or Promise<Config>
17
*/
18
function parseConfig(
19
configFilePath?: string,
20
cliOptions?: Object,
21
parseOptions?: {
22
promiseConfig?: boolean; // Return Promise<Config> instead of Config
23
throwErrors?: boolean; // Throw errors instead of process.exit
24
}
25
): Config | Promise<Config>;
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
const karma = require('karma');
32
33
// Parse default configuration file
34
const config = karma.config.parseConfig();
35
36
// Parse specific config file
37
const config = karma.config.parseConfig('./my-karma.conf.js');
38
39
// Parse with CLI overrides
40
const config = karma.config.parseConfig('./karma.conf.js', {
41
singleRun: true,
42
browsers: ['Chrome'],
43
port: 8080
44
});
45
46
// Async parsing
47
const config = await karma.config.parseConfig('./karma.conf.js', {}, {
48
promiseConfig: true,
49
throwErrors: true
50
});
51
52
// Using createPatternObject utility
53
const pattern = karma.config.createPatternObject({
54
pattern: 'test/**/*.js',
55
included: true,
56
served: true,
57
watched: true
58
});
59
60
console.log('Pattern weight:', pattern.weight);
61
console.log('Is watched:', pattern.watched);
62
```
63
64
### Configuration Object Structure
65
66
The main configuration object contains all Karma settings.
67
68
```javascript { .api }
69
/**
70
* Main Karma configuration class
71
*/
72
class Config {
73
// Server configuration
74
port: number; // Server port (default: 9876)
75
hostname: string; // Server hostname (default: 'localhost')
76
listenAddress: string; // Listen address (default: '0.0.0.0')
77
urlRoot: string; // URL root path (default: '/')
78
protocol: string; // Protocol (default: 'http:')
79
httpsServerOptions: Object; // HTTPS server options
80
81
// File configuration
82
basePath: string; // Base path for resolving files
83
files: (string | Pattern)[]; // Files to serve and watch
84
exclude: string[]; // Files to exclude
85
preprocessors: { [key: string]: string[] }; // File preprocessors
86
87
// Browser configuration
88
browsers: string[]; // Browsers to launch
89
customLaunchers: { [key: string]: any }; // Custom browser configurations
90
browserDisconnectTimeout: number; // Browser disconnect timeout (default: 2000)
91
browserDisconnectTolerance: number; // Browser disconnect tolerance (default: 0)
92
browserNoActivityTimeout: number; // Browser activity timeout (default: 30000)
93
captureTimeout: number; // Browser capture timeout (default: 60000)
94
95
// Test execution
96
singleRun: boolean; // Run once and exit (default: false)
97
autoWatch: boolean; // Watch files for changes (default: true)
98
watchOptions: { [key: string]: any }; // File watching options
99
restartOnFileChange: boolean; // Restart on file changes (default: false)
100
101
// Reporting
102
reporters: string[]; // Reporters to use (default: ['progress'])
103
colors: boolean; // Colored output (default: true)
104
logLevel: string; // Log level (default: 'INFO')
105
loggers: any[]; // Custom loggers
106
107
// Framework and plugins
108
frameworks: string[]; // Testing frameworks (e.g., ['jasmine'])
109
plugins: string[]; // Karma plugins to load
110
111
// Advanced options
112
client: { [key: string]: any }; // Client-side configuration
113
middleware: string[]; // Custom middleware
114
proxies: { [key: string]: string }; // URL proxies
115
upstreamProxy: { [key: string]: any }; // Upstream proxy configuration
116
retryLimit: number; // Test retry limit
117
detached: boolean; // Run in detached mode
118
crossOriginAttribute: boolean; // Add crossorigin attribute to script tags
119
failOnEmptyTestSuite: boolean; // Fail on empty test suite
120
concurrency: number; // Browser concurrency limit
121
122
// Advanced options
123
client: { [key: string]: any }; // Client-side configuration
124
middleware: string[]; // Custom middleware
125
proxies: { [key: string]: string }; // URL proxies
126
upstreamProxy: { [key: string]: any }; // Upstream proxy configuration
127
retryLimit: number; // Test retry limit (default: 2)
128
detached: boolean; // Run in detached mode (default: false)
129
crossOriginAttribute: boolean; // Cross-origin attribute (default: true)
130
131
// Coverage and reporting
132
coverageReporter: { [key: string]: any }; // Coverage reporter configuration
133
junitReporter: { [key: string]: any }; // JUnit reporter configuration
134
135
// Performance and concurrency
136
concurrency: number; // Browser concurrency (default: Infinity)
137
browserSocketTimeout: number; // Browser socket timeout (default: 20000)
138
pingTimeout: number; // Socket.IO ping timeout (default: 5000)
139
processKillTimeout: number; // Process kill timeout (default: 2000)
140
141
// File serving
142
usePolling: boolean; // Use polling for file watching
143
pollInterval: number; // Polling interval
144
httpModule: string; // HTTP module to use
145
forceJSONP: boolean; // Force JSONP transport
146
transports: string[]; // Socket.IO transports
147
}
148
```
149
150
### Pattern Classes
151
152
Karma uses Pattern classes to define how files are handled - whether they're served, included in tests, watched for changes, or cached.
153
154
```javascript { .api }
155
/**
156
* File pattern configuration class
157
*/
158
class Pattern {
159
/**
160
* Create new pattern instance
161
* @param pattern - File pattern (glob or path)
162
* @param served - Serve file to browser (default: true)
163
* @param included - Include in test execution (default: true)
164
* @param watched - Watch for changes (default: true)
165
* @param nocache - Disable caching (default: false)
166
* @param type - File type override
167
* @param isBinary - Binary file flag
168
* @param integrity - Subresource integrity hash
169
*/
170
constructor(
171
pattern: string,
172
served?: boolean,
173
included?: boolean,
174
watched?: boolean,
175
nocache?: boolean,
176
type?: string,
177
isBinary?: boolean,
178
integrity?: string
179
);
180
181
pattern: string; // File pattern
182
served: boolean; // File is served to browser
183
included: boolean; // File is included in test run
184
watched: boolean; // File is watched for changes
185
nocache: boolean; // File caching disabled
186
weight: number; // Pattern matching weight
187
type?: string; // MIME type override
188
isBinary?: boolean; // Binary file indicator
189
integrity?: string; // Subresource integrity hash
190
191
/**
192
* Compare pattern weights for sorting
193
* @param other - Other pattern to compare
194
* @returns Comparison result
195
*/
196
compare(other: Pattern): number;
197
}
198
199
/**
200
* URL pattern for external resources
201
* @extends Pattern
202
*/
203
class UrlPattern extends Pattern {
204
/**
205
* Create URL pattern for external resources
206
* @param url - URL to external resource
207
* @param type - MIME type override
208
* @param integrity - Subresource integrity hash
209
*/
210
constructor(url: string, type?: string, integrity?: string);
211
}
212
213
/**
214
* Create pattern object from string or configuration
215
* @param pattern - Pattern string or configuration object
216
* @returns Pattern or UrlPattern instance
217
*/
218
function createPatternObject(pattern: string | Object): Pattern | UrlPattern;
219
```
220
221
**Usage Examples:**
222
223
```javascript
224
module.exports = function(config) {
225
config.set({
226
files: [
227
// Simple string patterns
228
'src/**/*.js',
229
'test/**/*.spec.js',
230
231
// Pattern objects
232
{
233
pattern: 'test/fixtures/**/*.json',
234
watched: false,
235
included: false,
236
served: true
237
},
238
239
// External URLs
240
{
241
pattern: 'https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js',
242
type: 'js'
243
}
244
]
245
});
246
};
247
```
248
249
### Configuration File Examples
250
251
Basic configuration file structure for different scenarios.
252
253
**JavaScript Configuration (karma.conf.js):**
254
255
```javascript
256
module.exports = function(config) {
257
config.set({
258
// Base path for resolving patterns
259
basePath: '',
260
261
// Testing framework
262
frameworks: ['jasmine'],
263
264
// Test files and source files
265
files: [
266
'src/**/*.js',
267
'test/**/*.spec.js'
268
],
269
270
// Files to exclude
271
exclude: [
272
'src/**/*.min.js'
273
],
274
275
// Preprocessors for files
276
preprocessors: {
277
'src/**/*.js': ['coverage'],
278
'test/**/*.js': ['babel']
279
},
280
281
// Reporters
282
reporters: ['progress', 'coverage'],
283
284
// Coverage configuration
285
coverageReporter: {
286
type: 'html',
287
dir: 'coverage/'
288
},
289
290
// Server configuration
291
port: 9876,
292
hostname: 'localhost',
293
colors: true,
294
logLevel: config.LOG_INFO,
295
296
// Browser configuration
297
browsers: ['Chrome'],
298
customLaunchers: {
299
ChromeHeadlessCI: {
300
base: 'ChromeHeadless',
301
flags: ['--no-sandbox', '--disable-web-security']
302
}
303
},
304
305
// Test execution
306
singleRun: true,
307
autoWatch: false,
308
concurrency: Infinity,
309
310
// Timeouts
311
browserDisconnectTimeout: 10000,
312
browserNoActivityTimeout: 60000,
313
captureTimeout: 60000
314
});
315
};
316
```
317
318
**TypeScript Configuration (karma.conf.ts):**
319
320
```typescript
321
import { Config } from 'karma';
322
323
export default function(config: Config) {
324
config.set({
325
frameworks: ['jasmine', '@angular-devkit/build-angular'],
326
327
files: [
328
'src/**/*.ts',
329
'test/**/*.spec.ts'
330
],
331
332
preprocessors: {
333
'src/**/*.ts': ['typescript', 'coverage'],
334
'test/**/*.ts': ['typescript']
335
},
336
337
typescriptPreprocessor: {
338
options: {
339
sourceMap: true,
340
target: 'ES5',
341
module: 'commonjs'
342
}
343
},
344
345
browsers: ['Chrome'],
346
singleRun: true
347
});
348
}
349
```
350
351
### Environment-Specific Configuration
352
353
Configuration can be customized based on environment variables or CLI arguments.
354
355
```javascript
356
module.exports = function(config) {
357
const isCI = process.env.CI === 'true';
358
const isDebug = process.argv.includes('--debug');
359
360
config.set({
361
browsers: isCI ? ['ChromeHeadless'] : ['Chrome'],
362
singleRun: isCI,
363
autoWatch: !isCI,
364
logLevel: isDebug ? config.LOG_DEBUG : config.LOG_INFO,
365
366
// CI-specific settings
367
...(isCI && {
368
browserDisconnectTolerance: 3,
369
browserNoActivityTimeout: 90000,
370
captureTimeout: 90000
371
})
372
});
373
};
374
```
375
376
### Plugin Configuration
377
378
Configure various Karma plugins through the configuration object.
379
380
```javascript { .api }
381
// Common plugin configurations
382
interface PluginConfigurations {
383
// Coverage plugin
384
coverageReporter: {
385
type: 'html' | 'lcov' | 'text' | 'cobertura';
386
dir: string;
387
subdir?: string;
388
file?: string;
389
check?: {
390
global: {
391
statements: number;
392
branches: number;
393
functions: number;
394
lines: number;
395
};
396
};
397
};
398
399
// JUnit reporter
400
junitReporter: {
401
outputDir: string;
402
outputFile: string;
403
suite: string;
404
useBrowserName: boolean;
405
};
406
407
// Browser stack launcher
408
browserStack: {
409
username: string;
410
accessKey: string;
411
project: string;
412
build: string;
413
};
414
415
// Webpack preprocessor
416
webpack: {
417
// Webpack configuration object
418
};
419
420
// Istanbul instrumenter
421
coverageIstanbulReporter: {
422
reports: string[];
423
dir: string;
424
combineBrowserReports: boolean;
425
fixWebpackSourcePaths: boolean;
426
};
427
}
428
```
429
430
**Usage Examples:**
431
432
```javascript
433
module.exports = function(config) {
434
config.set({
435
plugins: [
436
'karma-jasmine',
437
'karma-chrome-launcher',
438
'karma-coverage',
439
'karma-webpack'
440
],
441
442
// Coverage configuration
443
coverageReporter: {
444
type: 'lcov',
445
dir: 'coverage/',
446
check: {
447
global: {
448
statements: 80,
449
branches: 75,
450
functions: 80,
451
lines: 80
452
}
453
}
454
},
455
456
// Webpack configuration
457
webpack: {
458
mode: 'development',
459
module: {
460
rules: [
461
{
462
test: /\.js$/,
463
exclude: /node_modules/,
464
use: 'babel-loader'
465
}
466
]
467
}
468
}
469
});
470
};
471
```