Code Coverage for Typescript using karma-jasmine and istanbul

走远了吗. 提交于 2019-12-03 02:54:19

Install karma-typescript:

npm install karma-typescript --save-dev

Put this in your karma.conf.js:

frameworks: ["jasmine", "karma-typescript"],

files: [
    { pattern: "src/**/*.ts" }
],

preprocessors: {
    "**/*.ts": ["karma-typescript"]
},

reporters: ["progress", "karma-typescript"],

browsers: ["Chrome"]

This will run your Typescript unit tests on the fly and generate Istanbul html coverage that look like this:

To run the above example you need to install a few packages:

npm install @types/jasmine jasmine-core karma karma-chrome-launcher karma-cli karma-jasmine karma-typescript typescript

This is the complete configuration for unit testing vanilla Typescript code, no tsconfig.json needed in this case. For more complex setups with Angular, React etc you can find examples in the examples folder and in the integration tests.

We are using instanbul-remap for our project and it works quite nicely. To create our coverage reports, we run the following shell script:

#!/bin/bash

PROJECT_PATH="$(dirname $0)/../"

cd $PROJECT_PATH
echo Creating coverage reports for `pwd`

if [ ! -d "target/dist" ]; then
  echo
  echo "target/dist directory not found. Must compile source with \`npm install\` before running tests."
  echo
  exit 1;
fi

COVERAGE_DIR=target/coverage-raw
REMAP_DIR=target/coverage-ts

mkdir -p $COVERAGE_DIR
mkdir -p $REMAP_DIR

# run coverage on unit tests only
echo Creating coverage reports for unit tests
node_modules/.bin/istanbul cover --dir $COVERAGE_DIR nodeunit `find target/dist/test/ -name *.test.js` > /dev/null

# re-map the coverage report so that typescript sources are shown
echo Remapping coverage reports for typescript
node_modules/.bin/remap-istanbul -i $COVERAGE_DIR/coverage.json -o $REMAP_DIR -t html

echo Coverage report located at $REMAP_DIR/index.html

Our project uses nodeunit as a test harness as it is a node application. However, I would expect that a similar approach would work for karma.

There is karma-remap-istanbul which integrates nicely remap-istanbul with karma. Documentation is pretty self explanatory but one thing - to have summary on the console the config is text: undefined (otherwise text output goes to the file).

So it is possible to have coverage summary directly from karma however when ts sources are not available in the same directory as karma.config.js karma-remap-istanbul still needs some more development regarding configuration to be able to generate full html reports.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!