Karma Proxies

Configuration File – Karma test runner

Overview #
In order to serve you well, Karma needs to know about your project in order to test it
and this is done via a configuration file. The easiest way to generate an initial configuration file
is by using the karma init command. This page lists all of the available configuration options.
Note: Most of the framework adapters, reporters, preprocessors and launchers need to be loaded as plugins.
The Karma configuration file can be written in JavaScript, CoffeeScript, or TypeScript and is loaded as a regular module.
Unless provided as argument, the Karma CLI will look for a configuration file at. /. /
in that order.
Within the configuration file, the configuration code is put together by setting module. exports to point to a function
which accepts one argument: the configuration object.
//
module. exports = function(config) {
({
basePath: ‘.. /.. ‘,
frameworks: [‘jasmine’],
//… });};
#
module. exports = (config) ->
basePath: ‘.. ‘
frameworks: [‘jasmine’]
#…
module. exports = (config) => {
//… });}
Customized TypeScript Configuration #
Under the hood Karma uses ts-node to transpile TypeScript to JavaScript. If the resolved has module configured as ES formats. You might get errors like SyntaxError: Unexpected token. This is due that in Node ES module formats are not supported. To overcome this issue you need to configure ts-node to use commonjs module format.
Create a JavaScript configuration file that overrides the module format.
require(‘ts-node’). register({
compilerOptions: {
module: ‘commonjs’}});
require(‘. /’);
File Patterns #
All of the configuration options, which specify file paths, use the minimatch library to facilitate flexible
but concise file expressions so you can easily list all of the files you want to include and exclude.
You can find details about each configuration option in the section below. The following options utilize minimatch expressions:
exclude
files
preprocessors
Examples:
**/* All files with a “js” extension in all subdirectories
**/! (jquery) Same as previous, but excludes “”
**/(foo|bar) In all subdirectories, all “” or “” files
Configuration Options #
These are all of the available configuration options.
autoWatch #
Type: Boolean
Default: true
CLI: –auto-watch, –no-auto-watch
Description: Enable or disable watching files and executing the tests whenever one of these files changes.
autoWatchBatchDelay #
Type: Number
Default: 250
Description: When Karma is watching the files for changes, it tries to batch
multiple changes into a single run so that the test runner doesn’t try to start and restart running
tests more than it should, or restart while build files are not in a consistent state. The configuration setting
tells Karma how long to wait (in milliseconds) from the last file change before starting
the test process again, resetting the timer each time a file changes (i. e. debouncing).
basePath #
Type: String
Default: ”
Description: The root path location that will be used to resolve all relative
paths defined in files and exclude. If the basePath configuration is a
relative path, then it will be resolved to the __dirname of the configuration file.
browserDisconnectTimeout #
Default: 2000
Description: How long does Karma wait for a browser to reconnect (in ms).
With a flaky connection, it is pretty common that the browser disconnects, but the actual test execution is still running
without any problems. Karma does not treat a disconnection as an immediate failure and will wait for browserDisconnectTimeout (ms).
If the browser reconnects during that time, everything is fine.
browserConsoleLogOptions #
Type: Object
Default: {level: “debug”, format: “%b%T:%m”, terminal: true}
Description: Configure how the browser console is logged with the following
properties, all of which are optional:
{
level: string,
format: string,
path: string,
terminal: boolean}
Here the level is the desired log-level, where level log always is logged. The format
is a string where%b, %t, %T, and%m are replaced with the browser string,
log type in lower-case, log type in uppercase, and log message, respectively. This format will
only effect the output file. path is the output-path of the output-file, and terminal indicates
if the log should be written in the terminal, or not.
browserDisconnectTolerance #
Default: 0
Description: The number of disconnections tolerated.
The disconnectTolerance value represents the maximum number of tries a browser will attempt in the case of a disconnection.
Usually, any disconnection is considered a failure, but this option allows you to define a tolerance level when there is
a flaky network link between the Karma server and the browsers.
browserNoActivityTimeout #
Default: 30000
Description: How long will Karma wait for a message from a browser before disconnecting from it (in ms).
If, during test execution, Karma does not receive any message from a browser within browserNoActivityTimeout(ms), it will disconnect from the browser. The default is the one recommended by Travis ()
browsers #
Type: Array
Default: []
CLI: –browsers Chrome, Firefox, –no-browsers
Possible Values:
Chrome (launcher requires karma-chrome-launcher plugin)
ChromeCanary (launcher requires karma-chrome-launcher plugin)
ChromeHeadless (launcher requires karma-chrome-launcher plugin ^2. 1. 0)
PhantomJS (launcher requires karma-phantomjs-launcher plugin)
Firefox (launcher requires karma-firefox-launcher plugin)
Opera (launcher requires karma-opera-launcher plugin)
IE (launcher requires karma-ie-launcher plugin)
Safari (launcher requires karma-safari-launcher plugin)
Description: A list of browsers to launch and capture. When Karma starts up, it will also start up each browser
which is placed within this setting. Once Karma is shut down, it will shut down these
browsers as well. You can capture any browser manually by opening the browser and visiting the URL where
the Karma web server is listening (by default it is localhost:9876/).
See config/browsers for more information. Additional launchers can be defined through plugins. Use the
–no-browsers command line option to override the value of this setting specified in the configuration file
with an empty list.
captureTimeout #
Default: 60000
Description: Timeout for capturing a browser (in ms).
The captureTimeout value represents the maximum boot-up time allowed for a browser to start and connect to Karma.
If any browser does not get captured within the timeout, Karma will kill it and try to launch
it again and, after three attempts to capture it, Karma will give up.
Default: undefined
CLI: All arguments after — (only when using karma run)
Description: When karma run is passed additional arguments on the command-line, they
are passed through to the test adapter as (an array of strings).
The option allows you to set this value for actions other than run.
How this value is used is up to your test adapter – you should check your adapter’s documentation to see how (and if) it uses this value.
eIframe #
Description: Run the tests inside an iFrame or a new window
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
iFrame and may need a new window to run.
nInParent #
Default: false
Description: Run the tests on the same window as the client, without using iframe or a new window
If true, Karma runs the tests inside the original window without using iframe. It will load the test scripts dynamically.
ptureConsole #
Description: Capture all console output and pipe it to the terminal.
earContext #
Description: Clear the context window
If true, Karma clears the context window upon the completion of running the tests. If false, Karma does not clear the context window
upon the completion of running the tests. Setting this to false is useful when embedding a Jasmine Spec Runner Template.
ientDisplayNone #
Description: Set style display none on client elements.
If true, Karma does not display the banner and browser list. Useful when using karma on component tests with screenshots.
colors #
CLI: –colors, –no-colors
Description: Enable or disable colors in the output (reporters and logs).
concurrency #
Default: Infinity
Description: How many browsers Karma launches in parallel.
Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited amount of browsers at once, and only start more when those have finished. Using this configuration, you can specify how many browsers should be running at once at any given point in time.
crossOriginAttribute #
Description: When true, this will append the crossorigin attribute to generated script tags, which enables better error reporting for JavaScript files served from a different origin.
Disable this when you need to load external scripts that are served without the necessary Access-Control-Allow-Origin header.
customContextFile #
Type: string
Default: null
Description: If null (default), uses karma’s own file.
customDebugFile #
customClientContextFile #
Description: If null (default), uses karma’s own file (which is used when nInParent set to true).
Description Custom HTTP headers that will be set upon serving files by Karma’s web server.
Custom headers are useful, especially with upcoming browser features like Service Workers.
The customHeaders option allows you to set HTTP headers for files that match a regular expression.
customHeaders is an array of Objects with properties as follows:
match: Regular expression string to match files
name: HTTP header name
value: HTTP header value
Example:
customHeaders: [{
match: ‘. *’,
name: ‘Service-Worker-Allowed’,
value: ‘/’}]
detached #
CLI: –detached
Description: When true, this will start the karma server in another process, writing no output to the console.
The server can be stopped using the karma stop command.
exclude #
Description: List of files/patterns to exclude from loaded files.
failOnEmptyTestSuite #
CLI: –fail-on-empty-test-suite, –no-fail-on-empty-test-suite
Description: Enable or disable failure on running empty test-suites. If disabled the program
will return exit-code 0 and display a warning.
failOnSkippedTests #
CLI: –fail-on-skipped-tests, –no-fail-on-skipped-tests
Description: Enable or disable failure on tests deliberately disabled, eg fit() or xit() tests in jasmine.
Use this to prevent accidental disabling tests needed to validate production.
failOnFailingTestSuite #
CLI: –fail-on-failing-test-suite, –no-fail-on-failing-test-suite
Description: Enable or disable failure on failing tests.
files #
Description: List of files/patterns to load in the browser.
See config/files for more information.
forceJSONP #
Description: Force to use JSONP polling instead of XHR polling.
frameworks #
Description: List of test frameworks you want to use. Typically, you will set this to [‘jasmine’], [‘mocha’] or [‘qunit’]…
Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via npm).
Additional information can be found in plugins.
listenAddress #
Default: ‘0. 0. 0’ or LISTEN_ADDR
Description: Address that the server will listen on. Change to ‘localhost’ to only listen to the loopback, or ‘::’ to listen on all IPv6 interfaces
hostname #
Default: ‘localhost’
Description: Hostname to be used when capturing browsers.
ServerOptions #
Default: {}
Description: Options object to be used by Node’s class.
Object description can be found in the API docs
ServerOptions: {
key: adFileSync(”, ‘utf8’),
cert: adFileSync(”, ‘utf8’)},
logLevel #
Type: Constant
Default: config. LOG_INFO
CLI: –log-level debug
Possible values:
config. LOG_DISABLE
config. LOG_ERROR
config. LOG_WARN
config. LOG_INFO
config. LOG_DEBUG
Description: Level of logging.
loggers #
Default: [{type: ‘console’}]
Description: A list of log appenders to be used. See the documentation for log4js for more information.
middleware #
Description: List of names of additional middleware you want the karma server to use. Middleware will be used in the order listed.
You must have installed the middleware via a plugin/framework (either inline or via npm). Additional information can be found in plugins.
The plugin must provide an express/connect middleware function (details about this can be found in the Express docs. An example of custom inline middleware is shown below.
function CustomMiddlewareFactory (config) {
return function (request, response, /* next */) {
response. writeHead(200)
return (“content! “)}}
middleware: [‘custom’]
plugins: [
{‘middleware:custom’: [‘factory’, CustomMiddlewareFactory]}… ]
mime #
Description: Redefine default mapping from file extensions to MIME-type
Set property name to required MIME, provide Array of extensions (without dots) as it’s value
mime: {
‘text/x-typescript’: [‘ts’, ‘tsx’]
‘text/plain’: [‘mytxt’]}
beforeMiddleware #
Description: This is the same as middleware except that these middleware will be run before karma’s own middleware.
plugins #
Default: [‘karma-*’]
Description: List of plugins to load. A plugin can be either a plugin object, or a string containing name of the module which exports a plugin object. See plugins for more information on how to install and use plugins.
By default, Karma loads plugins from all sibling npm packages which have a name starting with karma-*.
port #
Default: 9876
CLI: –port 9876
Description: The port where the web server will be listening.
If the defined port is already in use, karma will automatically increase its value in steps of 1 until a free port is found.
processKillTimeout #
Description: How long will Karma wait for browser process to terminate before sending a SIGKILL signal.
If, after test execution or after Karma attempts to kill the browser, browser is not killed within processKillTimeout(ms), Karma will send a SIGKILL signal to attempt to kill the browser forcefully.
preprocessors #
Default: {‘**/*’: ‘coffee’}
Description: A map of preprocessors to use.
Preprocessors can be loaded through plugins.
Note: Just about all preprocessors in Karma require an additional library to be installed (via npm).
Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance,
if you are using the “coverage” preprocessor on your source files, if you then attempt to interactively debug
your tests, you’ll discover that your expected source code is completely changed from what you expected. Because
of that, you’ll want to engineer this so that your automated builds use the coverage entry in the “reporters” list,
but your interactive debugging does not.
Click here for more information.
protocol #
Default: ‘:’
Possible Values:::
Description: Protocol used for running the Karma webserver.
Determines the use of the Node or class.
Note: Using ‘:’ requires you to specify ServerOptions.
Module #
Description: Module used for Karma webserver.
Uses the provided module instead of node’s built in or module. The module loaded here must exactly match the interface of node’s module. This can be useful for loading in a module like node-2 to allow for 2 support.
Note: if you’re using this to enable 2 you must also set the protocol to: and specify certificates as 2 can only run of.
proxies #
Description: A map of path-proxy pairs.
The proxy can be specified directly by the target url or path, or with an object to configure more options. The available options are:
target The target url or path (mandatory)
changeOrigin Whether or not the proxy should override the Host header using the host from the target (default false)
proxies: {
‘/static’: ”,
‘/web’: ‘localhost:9000’,
‘/img/’: ‘/base/test/images/’,
‘/proxyfied’: {
‘target’: ”,
‘changeOrigin’: true}},
proxyValidateSSL #
Description: Whether or not Karma or any browsers should raise an error when an invalid SSL certificate is found.
reportSlowerThan #
Description: Karma will report all the tests that are slower than given time limit (in ms).
This is disabled by default (since the default value is 0).
reporters #
Default: [‘progress’]
CLI: –reporters progress, growl
dots
progress
Description: A list of reporters to use.
Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins.
Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via npm).
formatError #
Type: Function
CLI: –format-error. /path/to/
Arguments:
msg – A single line of the assertion error and stack trace (called for each line).
Returns: A new error message line.
Description: Format assertion errors and stack traces. Useful for removing vendors and compiled sources. Return an empty line ” to remove it.
The CLI option should be a path to a file that exports the format function. This can be a function exported at the root of the module or an export named formatError.
pingTimeout #
Type Number
Default 5000
Description pingTimeout in ms, Very slow networks may need values up to 60000. Larger values delay discovery of deadlock in tests or browser crashes.
restartOnFileChange #
Description: When Karma is watching the files for changes, it will delay a new run until
the current run is finished. Enabling this setting will cancel the current run and start a new run
immediately when a change is detected.
retryLimit #
Default: 2
Description: When a browser crashes, karma will try to relaunch. This defines how many times karma should relaunch
a browser before giving up.
singleRun #
CLI: –single-run, –no-single-run
Description: Continuous Integration mode.
If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending
on whether all tests passed or any tests failed.
transports #
Default: [‘polling’, ‘websocket’]
Description: An array of allowed transport methods between the browser and testing server. This configuration setting
is handed off to (which manages the communication
between browsers and the testing server).
proxyReq #
Description: Called when requesting Proxy.
Details about this can be found in the node–proxy. An example of overwriting the HTTP header is shown below.
proxyReq: function(proxyReq, req, res, options) {
tHeader(‘Referer’, ”);}
proxyRes #
Description: Called when respnsing Proxy.
proxyRes: function(proxyRes, req, res) {
if (proxyRes. headers[‘set-cookie’]) {
proxyRes. headers[‘set-cookie’] = proxyRes. headers[‘set-cookie’](function (cookie) {
return place(/\s*secure;? /i, ”);})}}
upstreamProxy #
Description: For use when the Karma server needs to be run behind a proxy that changes the base url, etc
If set then the following fields will be defined and can be overridden:
path #
Default: ‘/’
Description: Will be prepended to the base url when launching browsers and prepended to internal urls as loaded by the browsers
Default: 9875
Description: Will be used as the port when launching browsers
Description: Will be used as the hostname when launching browsers
Description: Will be used as the protocol when launching browsers
urlRoot #
Description: The base url, where Karma runs.
All of Karma’s urls get prefixed with the urlRoot. This is helpful when using proxies, as
sometimes you might want to proxy a url that is already taken by Karma.
browserSocketTimeout #
Default: 20000
Description: Timeout for the client socket connection (in ms).
This configuration represents the amount of time that the client will wait for the socket
to connect.
When running a browser in different environments, it can take different amounts of time for the
client socket to connect. If Karma cannot connect within the default timeout, you may see an
error similar to the following:
ChromeHeadless have not captured in 60000ms, killing.
Trying to start ChromeHeadless again (1/2).
Trying to start ChromeHeadless again (2/2).
ChromeHeadless failed 2 times(timeout). Giving up.
If you see this error, you can try increasing the socket connection timeout.
Angular: Karma Proxy Configuration - DEV Community

Angular: Karma Proxy Configuration – DEV Community

John Peters
Posted on
Apr 21, 2020
• Updated on Apr 30, 2020
The way that Karma works is that it spins up it’s own web server on a pre-configured port, found in the file in the root of your Angular project.
reporters: [“progress”, “kjhtml”],
port: 9876, <-------------- colors: true, logLevel: config. LOG_INFO, autoWatch: true, browsers: ["Chrome"], singleRun: false, Enter fullscreen mode Exit fullscreen mode When we type in ng test we see our test in chrome start as shown here: So far so good, except for one thing. Your component's outbound requests are being sent to the Karma port (9876) instead of your regular back-end port (8180). You see nothing but 404's being returned because Karma has no endpoint listeners. The "real" listeners are running from a different server on port 8180. How do we redirect these requests? Karma Proxy Configuration The file has a section named proxies. It's here that we will configure what amounts to a port redirect. Let's take a look at that configuration. // Three examples of different URL paths being redirected to port 8180 proxies: { "/Admin/Credential": "localhost:8180", "/Person": "localhost:8180", "/Process/Queue/Status": "localhost:8180", }, Notice that all right hand side values contain the redirected port in the form of localhost:8180 The Rules: The URL Parts 1) Each proxy configuration has two parts: 1) The left side, to match the outbound path patterns and 2) The right side which is the "redirection". It includes the Schema, port but not the path. This is because the proxy redirects to the same path. 2) The left side path patterns do not include the schema or ports and must include the "/" as the first character in matching the path of the URL. 3) You still need to configure CORS support on the back-end because the outbound requests look like this: What's odd about this, is that the outbound URL is still sent using the Karma port! However, the request headers now contain, Host, Referer, and Sec-Fetch data. It looks like nothing has changed. Right? Indeed, if your back-end doesn't allows CORS the, request above will not work. Backend CORS Configuration in Core Add this in services section: And this in the Configure section: This allows the backend to receive and service the requests. Karma Proxy Configuration Internals When we want to "really" understand things we have to keep dropping down to the layer which confirms reality. In this case we ran a Network Trace to actually see what's happening a the network layer. Notice that there is never a 8080 port in the conversation? This agrees with what the browser's network information showed us. We do see our Karma port (9876). What's interesting is the port 63269, this is something Karma decides to open; which originates the outbound call GET /Administration/Service (not to 8180) but to 9876. We next see the ACK to this request followed by the response of 9876 to this "other port". Indeed this is what we see in the Chrome network tab as the response, if we click the preview tab. The data just "magically" comes back to the Karma socket. The Karma port is delivering the data to 63269! It's all mirrors and is probably the implementation of CORS protocol. In a future article we'll take a more in-depth looks at CORS. JWP2020 Karma proxies are not working - Stack Overflow

Karma proxies are not working – Stack Overflow

I am using Karma (v0. 12. 37) as test runner along with JSPM (v0. 16. 2). I have added following proxy config in karma so as to allow proper loading of JSPM files:
proxies: {
‘/base/jspm_packages/’: ‘/base/app/jspm_packages/’}
Bu this doesn’t work out and fails on following:
PhantomJS 2. 0. 0 (Windows 8 0. 0) ERROR: ‘Potentially unhandled rejection [10] Error: XHR error loading localhost:9876/base/jspm_packages/npm/
Error loading localhost:9876/base/jspm_packages/npm/
Error loading localhost:9876/base/app/pages/examples/todo-example/’
Debug Logs are giving:
proxying request – /base/jspm_packages/npm/ to localhost:9876
/base/app/jspm_packages/npm/ { host: ‘localhost’,
port: 9876,
baseProxyUrl: ‘/base/app/jspm_packages/’, : false}
But the following url containing ‘app’ in it works properly:
localhost:9876/base/ app/ jspm_packages/npm/
Any clue on what is going wrong?
asked Sep 7 ’15 at 9:01
Try:
‘/app/’: ‘/base/app/’,
‘/jspm_packages/’: ‘/base/jspm_packages/’}
answered Sep 18 ’15 at 22:31
tophemantopheman6, 6094 gold badges22 silver badges33 bronze badges
1
If you have configured your jspm-config with a baseUrl of “/”, try removing the baseUrl entry since karma-jspm does not support a custom baseUrl. Then you should be able to get rid of the “proxies” entry for the jspm_packages.
See:
Glen Selle3, 8974 gold badges35 silver badges59 bronze badges
answered Oct 9 ’15 at 15:38
brass monkeybrass monkey3, 87510 gold badges26 silver badges50 bronze badges
After having done lot of trial and error, found out the following way:
Instead of playing with proxies, alter the jspm paths config in
jspm: {…
paths: {
“github:*”: “app/jspm_packages/github/*”,
“npm:*”: “app/jspm_packages/npm/*”,
‘app/*’: ‘app/*’},… },
answered Oct 14 ’15 at 18:00
What finally did the trick for me (karma, babel, JSPM/SystemJS) was to have this:
Remove baseUrl from the and have this jspm section:
jspm: {
config: ”,
loadFiles: [
‘www/**/*’],
serveFiles: [
‘www/**/! (*spec)’],
“github:*”: “/base/jspm_packages/github/*”,
“npm:*”: “/base/jspm_packages/npm/*”,
‘www/*’: ‘/base/www/*’}},
answered Feb 9 ’16 at 11:11
mgamsjagermgamsjager4234 silver badges11 bronze badges
Not the answer you’re looking for? Browse other questions tagged proxy karma-runner jspm or ask your own question.

Frequently Asked Questions about karma proxies

Leave a Reply

Your email address will not be published. Required fields are marked *