README
karma-typescript
Karma :heart: Typescript
- Run unit tests written in Typescript with full type checking, seamlessly without extra build steps or scripts.
- Get remapped test coverage with Istanbul.
- Use plain Typescript or a framework: Angular, AngularJS, React, Sinon, any framework of choice.
Installation
The easiest way is to keep karma-typescript
as a devDependency in package.json
:
{
"devDependencies": {
"karma": "^6.1.0",
"karma-typescript": "5.5.1"
}
}
Do this by installing the plugin via npm:
npm install --save-dev karma-typescript
Configuration
Bare minimum configuration can be achieved with the following karma.conf.js
file:
module.exports = function(config) {
config.set({
frameworks: ["jasmine", "karma-typescript"],
files: [
"src/**/*.ts" // *.tsx for React Jsx
],
preprocessors: {
"**/*.ts": "karma-typescript" // *.tsx for React Jsx
},
reporters: ["progress", "karma-typescript"],
browsers: ["Chrome"]
});
};
The above example will compile all Typescript files and run the unit tests, producing remapped coverage in ./coverage
.
Examples
Frameworks and Integrations
Other examples
Sample applications by users
Transforms:
- karma-typescript-angular2-transform
- karma-typescript-cssmodules-transform
- karma-typescript-es6-transform
- karma-typescript-postcss-transform
Example output
Advanced configuration
The plugin has default settings for the compiler, instrumenting files and creating reports etc, which should suit most needs.
These are the default compiler settings:
karmaTypescriptConfig: {
compilerOptions: {
emitDecoratorMetadata: true,
experimentalDecorators: true,
jsx: "react",
module: "commonjs",
sourceMap: true,
target: "ES5"
},
exclude: ["node_modules"]
}
If the defaults aren't enough, the settings can be configured from karma.conf.js
:
karmaTypescriptConfig.bundlerOptions.addNodeGlobals - Boolean indicating whether the global variables
process
andBuffer
should be added to the bundle.
Defaults totrue
.karmaTypescriptConfig.bundlerOptions.constants - An object literal with keys/values which will be available as global variables in the bundle. The keys are expected to be strings and any non-string value will be stringified with
JSON.stringify
.Configuration example:
constants: { __STRING__: JSON.stringify("abc" + 123), __BOOLEAN__: true, "process.env": { "VARIABLE": "value" } }
Code example:
declare var __STRING__: string; declare var __BOOLEAN__: boolean; console.log(__STRING__, __BOOLEAN__, process.env.VARIABLE);
karmaTypescriptConfig.bundlerOptions.entrypoints - A
RegExp
filtering which files loaded by Karma should be executed in a test run, for example only filenames ending with ".spec.ts":/\.spec\.ts$/
.
This setting can be used to make sure the specs have finished setting up the test environment before other code starts requiring modules, which otherwise could lead to subtle bugs caused by race conditions.
When filtering file paths, beware that Windows uses\
while UNIX-like systems use/
as path separator.
Defaults to all files,/.*/
.karmaTypescriptConfig.bundlerOptions.exclude - An array of npm module names that will be excluded from the bundle.
karmaTypescriptConfig.bundlerOptions.ignore - An array of npm module names that will be bundled as stubs, ie
module.exports = {};
.karmaTypescriptConfig.bundlerOptions.noParse - An array of module names that will be bundled without being parsed for dependencies.
karmaTypescriptConfig.bundlerOptions.resolve.alias - An object literal where the key is a module name and the value is a path that will be used when resolving the module.
The key is a string.karmaTypescriptConfig.bundlerOptions.resolve.extensions - An array of file extensions to use, in order, when resolving modules.
Defaults to[".js", ".json", ".mjs", ".ts", ".tsx"]
.karmaTypescriptConfig.bundlerOptions.resolve.directories - An array of directories where modules will be recursively looked up.
Defaults to["node_modules"]
.karmaTypescriptConfig.bundlerOptions.sourceMap - A boolean indicating whether source maps should be generated for imported modules in the bundle, useful for debugging in a browser. For more debugging options, please see
karmaTypescriptConfig.coverageOptions.instrumentation
. Defaults tofalse
.karmaTypescriptConfig.bundlerOptions.transforms - An array of functions altering or replacing compiled Typescript code/Javascript code loaded from
node_modules
before bundling it. For more detailed documentation on transforms, please refer to the Transforms API section in this document.karmaTypescriptConfig.bundlerOptions.validateSyntax - A boolean indicating whether the syntax of the bundled code should be validated. Setting this to
false
may speed up bundling for large projects with lots of imports fromnode_modules
.
Defaults totrue
.karmaTypescriptConfig.compilerDelay - The number of milliseconds the compiler waits before compiling the project on each run. For projects with a large number of files it might be necessary to increase this value to make sure the compiler has collected all files before firing. Defaults to 250 ms.
karmaTypescriptConfig.compilerOptions - This setting will override or add to existing compiler options.
Valid options are the same as for thecompilerOptions
section intsconfig.json
, with the exception ofoutDir
andoutFile
which are ignored since the code is compiled in-memory.If
noEmitOnError
is set to a truthy value, in eithertsconfig.json
or inkarmaTypescriptConfig.compilerOptions
, the karma process will exit withts.ExitStatus.DiagnosticsPresent_OutputsSkipped
if any compilation errors occur.karmaTypescriptConfig.coverageOptions.instrumentation - A boolean indicating whether the code should be instrumented, set this property to
false
to see the original Typescript code when debugging. Please note that setting this property totrue
requires the Typescript compiler optionsourceMap
to also be set totrue
. For more debugging options, please seekarmaTypescriptConfig.coverageOptions.sourceMap
.
Defaults totrue
.karmaTypescriptConfig.coverageOptions.instrumenterOptions - Pass options to the
istanbul
instrumenter, ie options supported by istanbul-lib-instrument:{ // Name of global coverage variable. coverageVariable: '__coverage__', // Preserve comments in output. preserveComments: false, // Generate compact code. compact: true, // Set to true to instrument ES6 modules. esModules: false, // Set to true to allow `return` statements outside of functions. autoWrap: false, // Set to true to produce a source map for the instrumented code. produceSourceMap: false, // Set to array of class method names to ignore for coverage. ignoreClassMethods: [], // A callback function that is called when a source map URL is found in the original code. // This function is called with the source file name and the source map URL. sourceMapUrlCallback: null, // Turn debugging on. debug: false, // Set plugins. plugins: [ 'asyncGenerators', 'bigInt', 'classProperties', 'classPrivateProperties', 'dynamicImport', 'importMeta', 'objectRestSpread', 'optionalCatchBinding', 'flow', 'jsx' ] };
karmaTypescriptConfig.coverageOptions.exclude - A
RegExp
object or an array ofRegExp
objects for filtering which files should be excluded from coverage instrumentation.
When filtering file paths, beware that Windows uses\
while UNIX-like systems use/
as path separator.
Defaults to/\.(d|spec|test)\.ts$/i
which excludes *.d.ts, *.spec.ts and *.test.ts (case insensitive).karmaTypescriptConfig.coverageOptions.threshold - An object with minimum coverage thresholds. The threshold values can be set on a global level and on a per-file level, with options to exclude files and directories, and override settings on a per-file basis using globbing patterns.
A positive value will be used as a minimum percentage, for examplestatements: 50
means that at least 50% of the statements should be covered by a test.
A negative value will be used as a maximum number of uncovered items, for examplelines: 10
means that no more than 10 uncovered lines are allowed.threshold: { global: { statements: 100, branches: 100, functions: -10, lines: 100, excludes: [ "src/foo/**/*.js" ] }, file: { statements: -10, branches: 100, functions: 100, lines: 100, excludes: [ "src/bar/**/*.js" ], overrides: { "src/file.js": { statements: 90 } } } }
karmaTypescriptConfig.coverageOptions.watermarks - An object with custom istanbul watermarks. Each value is an array consisting of a lower and upper bound. If code coverage is above the upper bound, this is considered "healthy", and many reports will print output in green. If code coverage is below the lower bound, this is considered "unhealthy", and many reports will print output in red. Yellow output is reserved for coverage in between the lower and upper bound.
watermarks: { lines: [75, 90], functions: [75, 90], branches: [75, 90], statements: [75, 90] }
karmaTypescriptConfig.exclude - File string patterns to be excluded by the compiler. This property may be an
array
or anobject
for more fine-grained control.- Array: The string values will be merged with existing options.
- Object: The string values will be merged with or replace existing options:
{ mode: "merge|replace", values: ["foo", "bar"] }
Defaults to
["node_modules"]
.karmaTypescriptConfig.include - File string patterns to be included by the compiler. This property may be an
array
or anobject
for more fine-grained control.- Array: The string values will be merged with existing options.
- Object: The string values will be merged with or replace existing options:
{ mode: "merge|replace", values: ["foo", "bar"] }
This option is available in Typescript ^2.0.0.
karmaTypescriptConfig.reports - The types of coverage reports that should be created when running the tests, defaults to an html report in the directory
./coverage
. Reporters are configured as"reporttype": destination
where the destination can be specified in three ways:- A
string
with a directory path, for example"html": "coverage"
. - An empty string or
null
. Writes the output to the console, for example"text-summary": ""
. This is only possible for a subset of the reports available. - An
object
with more fine-grained control over path and filename:
"cobertura": { "directory": "coverage", // optional, defaults to 'coverage' "subdirectory": "cobertura" // optional, defaults to the name of the browser running the tests "filename": "coverage.xml", // optional, defaults to the report name } // "subdirectory" may also be a function that returns a directory from a given browser "cobertura": { "directory": "coverage", "subdirectory": function(browser) { // normalizes browser name directories to lowercase without version // ex: coverage/chrome/coverage.xml return browser.name.toLowerCase().split(' ')[0]; }, "filename": "coverage.xml" }
Available report types:
"clover": destination
"cobertura": destination
"html": destination
"html-spa": destination
"json-summary": destination
"json": destination
"lcovonly": destination
"teamcity": destination
(redirects to the console with destination "" ornull
)"text-lcov": destination
(redirects to the console with destination "" ornull
)"text-summary": destination
(redirects to the console with destination "" ornull
)"text": destination
(redirects to the console with destination "" ornull
)
Example of the three destination types:
karmaTypescriptConfig: { reports: { "cobertura": { "directory": "coverage", "filename": "coverage.xml", "subdirectory": "cobertura" }, "html": "coverage", "text-summary": "" } }
- A
karmaTypescriptConfig.transformPath - A function for renaming compiled file extensions to
.js
.
Defaults to renaming.ts
and.tsx
to.js
.karmaTypescriptConfig.tsconfig - A path to a
tsconfig.json
file.
The default compiler options will be replaced by the options in this file.
The directory of thetsconfig.json
file will be used as the base path for the Typescript compiler, and ifkarmaTypescriptConfig.tsconfig
isn't set, thebasePath
property of the Karma config will be used as the compiler base path instead.karmaTypescriptConfig.stopOnFailure - Stop on any compiler error.
By default karma will stop when any typescript compile errors are encountered.
Setting this to false will allow tests to be run when typescript compile errors are present.
Example of a full karmaTypescriptConfig
configuration:
karmaTypescriptConfig: {
bundlerOptions: {
addNodeGlobals: true,
constants: {
__PRODUCTION__: false
},
entrypoints: /\.spec\.(ts|tsx)$/,
exclude: ["react/addons"],
ignore: ["ws"],
noParse: "jquery",
resolve: {
alias: {
"@angular/upgrade/static