UNPKG

25.3 kBTypeScriptView Raw
1// Type definitions for karma 5.0
2// Project: https://github.com/karma-runner/karma, http://karma-runner.github.io
3// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
4// James Garbutt <https://github.com/43081j>
5// Yaroslav Admin <https://github.com/devoto13>
6// Piotr Błażejewicz <https://github.com/peterblazejewicz>
7// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8// TypeScript Version: 3.2
9
10/// <reference types="node" />
11
12// See Karma public API https://karma-runner.github.io/latest/dev/public-api.html
13import https = require('https');
14import { Appender } from 'log4js';
15import { EventEmitter } from 'events';
16import * as constants from './lib/constants';
17import { VERSION } from './lib/constants';
18
19export { constants, VERSION };
20/**
21 * `start` method is deprecated since 0.13. It will be removed in 0.14.
22 * Please use
23 * <code>
24 * server = new Server(config, [done])
25 * server.start()
26 * </code>
27 * instead.
28 *
29 * @deprecated
30 */
31export const server: DeprecatedServer;
32export const runner: Runner;
33export const stopper: Stopper;
34
35export namespace launcher {
36 class Launcher {
37 static generateId(): string;
38
39 constructor(emitter: NodeJS.EventEmitter, injector: any);
40
41 // TODO: Can this return value ever be typified?
42 launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[];
43 kill(id: string, callback: () => void): boolean;
44 restart(id: string): boolean;
45 killAll(callback: () => void): void;
46 areAllCaptured(): boolean;
47 markCaptured(id: string): void;
48 }
49}
50
51/** @deprecated */
52export interface DeprecatedServer {
53 /** @deprecated */
54 start(options?: any, callback?: ServerCallback): void;
55}
56
57export interface Runner {
58 run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;
59}
60
61export interface Stopper {
62 /**
63 * This function will signal a running server to stop. The equivalent of karma stop.
64 */
65 stop(options?: ConfigOptions, callback?: ServerCallback): void;
66}
67
68export interface TestResults {
69 disconnected: boolean;
70 error: boolean;
71 exitCode: number;
72 failed: number;
73 success: number;
74}
75
76export class Server extends EventEmitter {
77 constructor(options?: ConfigOptions | ConfigFile, callback?: ServerCallback);
78 /**
79 * Start the server
80 */
81 start(): void;
82 /**
83 * Get properties from the injector
84 * @param token
85 */
86 get(token: string): any;
87 /**
88 * Force a refresh of the file list
89 */
90 refreshFiles(): Promise<any>;
91
92 on(event: string, listener: (...args: any[]) => void): this;
93
94 /**
95 * Listen to the 'run_complete' event.
96 */
97 on(event: 'run_complete', listener: (browsers: any, results: TestResults) => void): this;
98
99 /**
100 * Backward-compatibility with karma-intellij bundled with WebStorm.
101 * Deprecated since version 0.13, to be removed in 0.14
102 */
103 // static start(): void;
104}
105
106export type ServerCallback = (exitCode: number) => void;
107
108export interface Config {
109 set: (config: ConfigOptions) => void;
110 LOG_DISABLE: string;
111 LOG_ERROR: string;
112 LOG_WARN: string;
113 LOG_INFO: string;
114 LOG_DEBUG: string;
115}
116
117export interface ConfigFile {
118 configFile: string;
119}
120
121// For documentation and intellisense list Karma browsers
122
123/**
124 * Available browser launchers
125 * - `Chrome` - launcher requires `karma-chrome-launcher` plugin
126 * - `ChromeCanary` - launcher requires `karma-chrome-launcher` plugin
127 * - `ChromeHeadless` - launcher requires `karma-chrome-launcher` plugin
128 * - `PhantomJS` - launcher requires `karma-phantomjs-launcher` plugin
129 * - `Firefox` - launcher requires `karma-firefox-launcher` plugin
130 * - `Opera` - launcher requires `karma-opera-launcher` plugin
131 * - `IE` - launcher requires `karma-ie-launcher` plugin
132 * - `Safari` - launcher requires karma-safari-launcher plugin
133 */
134export type AutomatedBrowsers =
135 | 'Chrome'
136 | 'ChromeCanary'
137 | 'ChromeHeadless'
138 | 'PhantomJS'
139 | 'Firefox'
140 | 'Opera'
141 | 'IE'
142 | 'Safari';
143
144export interface CustomHeaders {
145 /** Regular expression string to match files */
146 match: string;
147 /** HTTP header name */
148 name: string;
149 /** HTTP header value */
150 value: string;
151}
152
153export interface ProxyOptions {
154 /** The target url or path (mandatory) */
155 target: string;
156 /**
157 * Whether or not the proxy should override the Host header using the host from the target
158 * @defult false
159 */
160 changeOrigin?: boolean;
161}
162
163/** A map of path-proxy pairs. */
164export interface PathProxyPairs {
165 [path: string]: string | ProxyOptions;
166}
167
168/** For use when the Karma server needs to be run behind a proxy that changes the base url, etc */
169export interface UpstreamProxy {
170 /**
171 * Will be prepended to the base url when launching browsers and prepended to internal urls as loaded by the browsers
172 * @default '/'
173 */
174 path?: string;
175 /**
176 * Will be used as the port when launching browsers
177 * @default 9875
178 */
179 port?: number;
180 /**
181 * Will be used as the hostname when launching browsers
182 * @default 'localhost'
183 */
184 hostname?: string;
185 /**
186 * Will be used as the protocol when launching browsers
187 * @default 'http'
188 */
189 protocol?: string;
190}
191
192// description of inline plugins
193export type PluginName = string;
194// tslint:disable-next-line:ban-types support for constructor function and classes
195export type ConstructorFn = Function | (new (...params: any[]) => any);
196export type FactoryFn = (...params: any[]) => any;
197export type ConstructorFnType = ['type', ConstructorFn];
198export type FactoryFnType = ['factory', FactoryFn];
199export type ValueType = ['value', any];
200export type InlinePluginType = FactoryFnType | ConstructorFnType | ValueType;
201export type InlinePluginDef = Record<PluginName, InlinePluginType>;
202
203export interface ConfigOptions {
204 /**
205 * @description Enable or disable watching files and executing the tests whenever one of these files changes.
206 * @default true
207 */
208 autoWatch?: boolean;
209 /**
210 * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run
211 * so that the test runner doesn't try to start and restart running tests more than it should.
212 * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred
213 * before starting the test process again.
214 * @default 250
215 */
216 autoWatchBatchDelay?: number;
217 /**
218 * @default ''
219 * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>.
220 * If the basePath configuration is a relative path then it will be resolved to
221 * the <code>__dirname</code> of the configuration file.
222 */
223 basePath?: string;
224 /**
225 * Configure how the browser console is logged with the following properties, all of which are optional
226 */
227 browserConsoleLogOptions?: BrowserConsoleLogOptions;
228 /**
229 * @default 2000
230 * @description How long does Karma wait for a browser to reconnect (in ms).
231 * <p>
232 * With a flaky connection it is pretty common that the browser disconnects,
233 * but the actual test execution is still running without any problems. Karma does not treat a disconnection
234 * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms).
235 * If the browser reconnects during that time, everything is fine.
236 * </p>
237 */
238 browserDisconnectTimeout?: number;
239 /**
240 * @default 0
241 * @description The number of disconnections tolerated.
242 * <p>
243 * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt
244 * in the case of a disconnection. Usually any disconnection is considered a failure,
245 * but this option allows you to define a tolerance level when there is a flaky network link between
246 * the Karma server and the browsers.
247 * </p>
248 */
249 browserDisconnectTolerance?: number;
250 /**
251 * @default 10000
252 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms).
253 * <p>
254 * If, during test execution, Karma does not receive any message from a browser within
255 * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser
256 * </p>
257 */
258 browserNoActivityTimeout?: number;
259 /**
260 * Timeout for the client socket connection (in ms)
261 * @default 20000
262 */
263 browserSocketTimeout?: number;
264 /**
265 * @default []
266 * Possible Values:
267 * <ul>
268 * <li>Chrome (launcher comes installed with Karma)</li>
269 * <li>ChromeCanary (launcher comes installed with Karma)</li>
270 * <li>PhantomJS (launcher comes installed with Karma)</li>
271 * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li>
272 * <li>Opera (launcher requires karma-opera-launcher plugin)</li>
273 * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li>
274 * <li>Safari (launcher requires karma-safari-launcher plugin)</li>
275 * </ul>
276 * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser
277 * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well.
278 * You can capture any browser manually by opening the browser and visiting the URL where
279 * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>).
280 */
281 browsers?: Array<AutomatedBrowsers | string>;
282 /**
283 * @default 60000
284 * @description Timeout for capturing a browser (in ms).
285 * <p>
286 * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a
287 * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma
288 * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up.
289 * </p>
290 */
291 captureTimeout?: number;
292 client?: ClientOptions;
293 /**
294 * @default true
295 * @description Enable or disable colors in the output (reporters and logs).
296 */
297 colors?: boolean;
298 /**
299 * @default 'Infinity'
300 * @description How many browsers Karma launches in parallel.
301 * Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited
302 * amount of browsers at once, and only start more when those have finished. Using this configuration,
303 * you can specify how many browsers should be running at once at any given point in time.
304 */
305 concurrency?: number;
306 /**
307 * When true, this will append the crossorigin attribute to generated script tags,
308 * which enables better error reporting for JavaScript files served from a different origin
309 * @default true
310 */
311 crossOriginAttribute?: boolean;
312 /**
313 * If null (default), uses karma's own context.html file.
314 * @default undefined
315 */
316 customContextFile?: string;
317 /**
318 * If null (default), uses karma's own client_with_context.html file (which is used when client.runInParent set to true).
319 * @default undefined
320 */
321 customClientContextFile?: string;
322 /**
323 * If null (default), uses karma's own debug.html file.
324 * @default undefined
325 */
326 customDebugFile?: string;
327 /**
328 * Custom HTTP headers that will be set upon serving files by Karma's web server.
329 * Custom headers are useful, especially with upcoming browser features like Service Workers.
330 * @default undefined
331 */
332 customHeaders?: CustomHeaders[];
333 customLaunchers?: { [key: string]: CustomLauncher };
334 /**
335 * When true, this will start the karma server in another process, writing no output to the console.
336 * The server can be stopped using the karma stop command.
337 * @default false
338 */
339 detached?: boolean;
340 /**
341 * @default []
342 * @description List of files/patterns to exclude from loaded files.
343 */
344 exclude?: string[];
345 /**
346 * Enable or disable failure on running empty test-suites.
347 * If disabled the program will return exit-code 0 and display a warning.
348 * @default true
349 */
350 failOnEmptyTestSuite?: boolean;
351 /**
352 * Enable or disable failure on tests deliberately disabled, eg fit() or xit() tests in jasmine.
353 * Use this to prevent accidental disabling tests needed to validate production.
354 * @default true
355 */
356 failOnSkippedTests?: boolean;
357 /**
358 * Enable or disable failure on failing tests.
359 * @default true
360 */
361 failOnFailingTestSuite?: boolean;
362 /**
363 * @default []
364 * @description List of files/patterns to load in the browser.
365 */
366 files?: Array<FilePattern | string>;
367 /**
368 * Force socket.io to use JSONP polling instead of XHR polling
369 * @default false
370 */
371 forceJSONP?: boolean;
372 /**
373 * A new error message line
374 * @default undefined
375 */
376 formatError?: (msg: string) => string;
377 /**
378 * @default []
379 * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...
380 * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
381 */
382 frameworks?: string[];
383 /**
384 * @default 'localhost'
385 * @description Hostname to be used when capturing browsers.
386 */
387 hostname?: string;
388 /**
389 * Module used for Karma webserver
390 * @default undefined
391 */
392 httpModule?: string;
393 /**
394 * @default {}
395 * @description Options object to be used by Node's https class.
396 * Object description can be found in the
397 * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener)
398 */
399 httpsServerOptions?: https.ServerOptions;
400 /**
401 * Address that the server will listen on. Change to 'localhost' to only listen to the loopback, or '::' to listen on all IPv6 interfaces
402 * @default '0.0.0.0' or `LISTEN_ADDR`
403 */
404 listenAddress?: string;
405 /**
406 * @default config.LOG_INFO
407 * Possible values:
408 * <ul>
409 * <li>config.LOG_DISABLE</li>
410 * <li>config.LOG_ERROR</li>
411 * <li>config.LOG_WARN</li>
412 * <li>config.LOG_INFO</li>
413 * <li>config.LOG_DEBUG</li>
414 * </ul>
415 * @description Level of logging.
416 */
417 logLevel?: string;
418 /**
419 * @default [{type: 'console'}]
420 * @description A list of log appenders to be used. See the documentation for [log4js] for more information.
421 */
422 loggers?: { [name: string]: Appender } | Appender[];
423 /**
424 * @default []
425 * @description List of names of additional middleware you want the
426 * Karma server to use. Middleware will be used in the order listed.
427 * You must have installed the middleware via a plugin/framework
428 * (either inline or via NPM). Additional information can be found in
429 * [plugins](http://karma-runner.github.io/2.0/config/plugins.html).
430 * The plugin must provide an express/connect middleware function
431 * (details about this can be found in the
432 * [Express](http://expressjs.com/guide/using-middleware.html) docs).
433 */
434 middleware?: string[];
435 /**
436 * This is the same as middleware except that these middleware will be run before karma's own middleware.
437 * @default []
438 */
439 beforeMiddleware?: string[];
440 /**
441 * @default {}
442 * @description Redefine default mapping from file extensions to MIME-type.
443 * Set property name to required MIME, provide Array of extensions (without dots) as it's value.
444 */
445 mime?: { [type: string]: string[] };
446 /**
447 * Socket.io pingTimeout in ms, https://socket.io/docs/server-api/#new-Server-httpServer-options.
448 * Very slow networks may need values up to 60000. Larger values delay discovery of deadlock in tests or browser crashes.
449 * @default 5000
450 */
451 pingTimeout?: number;
452 /**
453 * @default ['karma-*']
454 * @description List of plugins to load. A plugin can be a string (in which case it will be required
455 * by Karma) or an inlined plugin - Object.
456 * By default, Karma loads all sibling NPM modules which have a name starting with karma-*.
457 * Note: Just about all plugins in Karma require an additional library to be installed (via NPM).
458 */
459 plugins?: Array<PluginName | InlinePluginDef>;
460 /**
461 * @default 9876
462 * @description The port where the web server will be listening.
463 */
464 port?: number;
465 /**
466 * How long will Karma wait for browser process to terminate before sending a SIGKILL signal
467 * @default 2000
468 */
469 processKillTimeout?: number;
470 /**
471 * @default {'**\/*.coffee': 'coffee'}
472 * @description A map of preprocessors to use.
473 *
474 * Preprocessors can be loaded through [plugins].
475 *
476 * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults)
477 * require an additional library to be installed (via NPM).
478 *
479 * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance,
480 * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug
481 * your tests, you'll discover that your expected source code is completely changed from what you expected. Because
482 * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list,
483 * but your interactive debugging does not.
484 *
485 */
486 preprocessors?: { [name: string]: string | string[] };
487 /**
488 * @default 'http:'
489 * Possible Values:
490 * <ul>
491 * <li>http:</li>
492 * <li>https:</li>
493 * </ul>
494 * @description Protocol used for running the Karma webserver.
495 * Determines the use of the Node http or https class.
496 * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>.
497 */
498 protocol?: string;
499 /**
500 * @default {}
501 * @description A map of path-proxy pairs
502 * The proxy can be specified directly by the target url or path, or with an object to configure more options
503 */
504 proxies?: PathProxyPairs;
505 /**
506 * Called when requesting Proxy
507 * @default undefined
508 */
509 proxyReq?: (proxyReq: any, req: any, res: any, options: object) => void;
510 /**
511 * Called when respnsing Proxy
512 * @default undefined
513 */
514 proxyRes?: (proxyRes: any, req: any, res: any) => void;
515 /**
516 * @default true
517 * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found.
518 */
519 proxyValidateSSL?: boolean;
520 /**
521 * @default 0
522 * @description Karma will report all the tests that are slower than given time limit (in ms).
523 * This is disabled by default (since the default value is 0).
524 */
525 reportSlowerThan?: number;
526 /**
527 * @default ['progress']
528 * Possible Values:
529 * <ul>
530 * <li>dots</li>
531 * <li>progress</li>
532 * </ul>
533 * @description A list of reporters to use.
534 * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins.
535 * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM).
536 */
537 reporters?: string[];
538 /**
539 * When Karma is watching the files for changes, it will delay a new run
540 * until the current run is finished. Enabling this setting
541 * will cancel the current run and start a new run immediately when a change is detected.
542 */
543 restartOnFileChange?: boolean;
544 /**
545 * When a browser crashes, karma will try to relaunch. This defines how many times karma should relaunch a browser before giving up.
546 * @default 2
547 */
548 retryLimit?: number;
549 /**
550 * @default false
551 * @description Continuous Integration mode.
552 * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending
553 * on whether all tests passed or any tests failed.
554 */
555 singleRun?: boolean;
556 /**
557 * @default ['polling', 'websocket']
558 * @description An array of allowed transport methods between the browser and testing server. This configuration setting
559 * is handed off to [socket.io](http://socket.io/) (which manages the communication
560 * between browsers and the testing server).
561 */
562 transports?: string[];
563 /**
564 * For use when the Karma server needs to be run behind a proxy that changes the base url, etc
565 */
566 upstreamProxy?: UpstreamProxy;
567 /**
568 * @default '/'
569 * @description The base url, where Karma runs.
570 * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as
571 * sometimes you might want to proxy a url that is already taken by Karma.
572 */
573 urlRoot?: string;
574}
575
576export interface ClientOptions {
577 /**
578 * @default undefined
579 * @description When karma run is passed additional arguments on the command-line, they
580 * are passed through to the test adapter as karma.config.args (an array of strings).
581 * The client.args option allows you to set this value for actions other than run.
582 * How this value is used is up to your test adapter - you should check your adapter's
583 * documentation to see how (and if) it uses this value.
584 */
585 args?: string[];
586 /**
587 * @default false
588 * @description Set style display none on client elements.
589 * If true, Karma does not display the banner and browser list.
590 * Useful when using karma on component tests with screenshots
591 */
592 clientDisplayNone?: boolean;
593 /**
594 * @default true
595 * @description Run the tests inside an iFrame or a new window
596 * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an
597 * iFrame and may need a new window to run.
598 */
599 useIframe?: boolean;
600 /**
601 * @default true
602 * @description Capture all console output and pipe it to the terminal.
603 */
604 captureConsole?: boolean;
605 /**
606 * @default false
607 * @description Run the tests on the same window as the client, without using iframe or a new window
608 */
609 runInParent?: boolean;
610 /**
611 * @default true
612 * @description Clear the context window
613 * If true, Karma clears the context window upon the completion of running the tests.
614 * If false, Karma does not clear the context window upon the completion of running the tests.
615 * Setting this to false is useful when embedding a Jasmine Spec Runner Template.
616 */
617 clearContext?: boolean;
618}
619
620/** type to use when including a file */
621export type FilePatternTypes = 'css' | 'html' | 'js' | 'dart' | 'module' | 'dom';
622
623export interface FilePattern {
624 /**
625 * The pattern to use for matching.
626 */
627 pattern: string;
628 /**
629 * @default true
630 * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched
631 * for changes.
632 */
633 watched?: boolean;
634 /**
635 * @default true
636 * @description Should the files be included in the browser using <script> tag? Use false if you want to
637 * load them manually, eg. using Require.js.
638 */
639 included?: boolean;
640 /**
641 * @default true
642 * @description Should the files be served by Karma's webserver?
643 */
644 served?: boolean;
645 /**
646 * Choose the type to use when including a file
647 * @default 'js'
648 * @description The type determines the mechanism for including the file.
649 * The css and html types create link elements; the js, dart, and module elements create script elements.
650 * The dom type includes the file content in the page, used, for example, to test components combining HTML and JS.
651 */
652 type?: FilePatternTypes;
653 /**
654 * @default false
655 * @description Should the files be served from disk on each request by Karma's webserver?
656 */
657 nocache?: boolean;
658}
659
660export interface CustomLauncher {
661 base: string;
662 browserName?: string;
663 flags?: string[];
664 platform?: string;
665}
666
667export interface BrowserConsoleLogOptions {
668 /** the desired log-level, where level log always is logged */
669 level?: 'log' | 'error' | 'warn' | 'info' | 'debug';
670 /**
671 * The format is a string where `%b`, `%t`, `%T`, and `%m` are replaced with the browser string,
672 * log type in lower-case, log type in uppercase, and log message, respectively.
673 * This format will only effect the output file
674 */
675 format?: string;
676 /** output-path of the output-file */
677 path?: string;
678 /** if the log should be written in the terminal, or not */
679 terminal?: boolean;
680}
681
682export namespace config {
683 function parseConfig(configFilePath: string, cliOptions: ConfigOptions): Config;
684}