Angular4 how to enable testing coverage

I am working on an Angular4 project.

I am trying to set up code coverage. I have created a very simple and small application.

I've read every possible page I could find, but I'm lost.

How do I set up code coverage in Angular4?

UPDATE2: Now I decided to use the Karma Coverage reporter https://www.npmjs.com/package/karma-coverage and therefore reworked the karma config file as described.

The json package has been updated.

Now I can see how the folder is being created, but the HTML file shows an empty table, enter image description here

The test runs and passes:

enter image description here not sure what to do next.

Here is my json package.

   {
  "name": "angular2-webpack",
  "version": "0.0.1",
  "description": "A webpack starter for Angular",
  "scripts": {
      "pretest": "npm run lint",
      "start": "webpack-dev-server --inline --progress --port 8080",
      "test": "karma start",
      "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
      "lint": "tslint --force \"src/**/*.ts\""
  },
  "license": "MIT",
    "dependencies": {
        "@angular/common": "4.1.2",
        "@angular/compiler": "4.1.2",
        "@angular/core": "4.1.2",
        "@angular/forms": "4.1.2",
        "@angular/http": "4.1.2",
        "@angular/platform-browser": "4.1.2",
        "@angular/platform-browser-dynamic": "4.1.2",
        "@angular/router": "4.1.2",
        "bootstrap": "^3.3.7",
        "core-js": "2.4.1",
        "es6-shim": "^0.35.3",
        "jquery": "^3.2.0",
        "reflect-metadata": "^0.1.10",
        "rxjs": "^5.0.1",
        "zone.js": "^0.8.10"
  },
  "devDependencies": {
      "@types/jasmine": "2.5.47",
      "@types/node": "^7.0.18",
      "angular2-template-loader": "^0.6.0",
      "awesome-typescript-loader": "^3.0.4",
      "css-loader": "^0.28.1",
      "extract-text-webpack-plugin": "^2.1.0",
      "file-loader": "^0.11.1",
      "html-loader": "^0.4.3",
      "html-webpack-plugin": "^2.16.1",
      "jasmine-core": "^2.4.1",
      "karma": "^1.7.0",
      "karma-chrome-launcher": "^2.0.0",
      "karma-coverage": "^1.1.1",
      "karma-jasmine": "^1.0.2",
      "karma-phantomjs-launcher": "^1.0.4",
      "karma-sourcemap-loader": "^0.3.7",
      "karma-webpack": "^2.0.1",
      "lint": "^1.1.2",
      "node-sass": "^4.5.0",
      "null-loader": "^0.1.1",
      "phantomjs-prebuilt": "^2.1.7",
      "raw-loader": "^0.5.1",
      "rimraf": "^2.5.2",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.17.0",
      "tslint": "^5.2.0",
      "tslint-loader": "^3.5.3",
      "typescript": "~2.3.2",
      "webpack": "^2.2.1",
      "webpack-dev-server": "2.4.5",
      "webpack-merge": "^4.1.0"
  }
}

      

As per my webpack config

var webpack = require('webpack');
var helpers = require('./helpers');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: process.env.NODE_ENV === "development"
});


module.exports = {
    devtool: 'inline-source-map',

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    {
                        loader: 'awesome-typescript-loader',
                        options: {configFileName: helpers.root('src', 'tsconfig.json')}
                    }, 'angular2-template-loader'
                ]
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: 'style-loader!css-loader?sourceMap'
            },
            {
                test: /\.css$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            },


            {
                test: /\.scss$/,
                exclude: helpers.root('src', 'app'),
                use: extractSass.extract({
                    use: [{
                        loader: "css-loader"
                    }, {
                        loader: "sass-loader"
                    }],
                    // use style-loader in development
                    fallback: "style-loader"
                })
            },
            {
                test: /\.scss$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            }
        ]
    },

    plugins: [
        extractSass,
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            helpers.root('./src'), // location of your src
            {} // a map of your routes
        )
    ]
}

      

Next, the updated karma config file is updated:

  var webpackConfig = require('./webpack.test');
var path = require('path');

var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
module.exports = function (config) {
    var _config = {
        basePath: './',

        frameworks: ['jasmine'],

        files: [
            {pattern: './config/karma-test-shim.js', watched: false},
            '../src/**/*.js'
        ],
        // list of files to exclude
        exclude: [],
        preprocessors: {
            './config/karma-test-shim.js': ['webpack', 'sourcemap'],
            '../src/**/*.js': ['coverage']

        },
        coverageReporter: {
            type : 'html',
            dir : 'cover/'
        },
        webpack: webpackConfig,

        webpackMiddleware: {
            stats: 'errors-only'
        },

        webpackServer: {
            noInfo: true
        },

        reporters: ['progress', 'mocha','coverage'],

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: isTestWatch ? ['PhantomJS'] : ['PhantomJS'],
        singleRun: true
    };

     config.set(_config);

};

      

The code in its full glory can be found here

https://github.com/uweDuesing/angular2-webpack-template

+3


source to share


4 answers


I don't know how to set it up from scratch, but I can tell that projects built with angular-cli have already set up the code coverage plugin. Check https://github.com/angular/angular-cli/wiki/test , you can run ng test -cc .



If you want to check how it is configured, generate the project with angular-cli and execute ng eject in the root folder , which will allow you to see the webpack config file.

+1


source


I researched various articles and in the simplest way I found: -

$ npm install karma karma-jasmine karma-chrome-launcher Karma-jasmine-html-reporter Karma-coverage-istanbul-reporter

$ ng test - code coverage



$ http-server -c-1 -o -p 9875./coverage

Open it only in Chrome browser.

+1


source


I had a similar problem trying to get the angular4 cli to work in setup after ng eject

. This turned out to be a few simple lines for me in package.json and karma.conf.js

maybe it will help someone else to do it from scratch or from a point of view ng eject

.

I added coverage

script to package.json

"test": "karma start ./karma.conf.js",
"coverage": "karma start --coverage true ./karma.conf.js",

      

Then for karma config I had to add a line for client.args and set angularCli.codeCoverage to a variable isCoverage

that I create to read the command line parameter from package.json.

// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {

  const isCoverage = config.coverage || false;

  console.log(`Generate Coverage Statistics?: ${isCoverage}`);

  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    client:{
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
      args: ['--coverage', config.coverage]
    },
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev',
      codeCoverage: isCoverage
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'coverage-istanbul']
              : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });

};

      

0


source


Add angularClt to your karma.conf file. Something like that:

angularCli: {
      environment: 'dev',
      codeCoverage: true
    }
      

Run codeHide result


codeCoverage is the important part if you want to run codeCoverage to fetch the app using script command npm run test

0


source







All Articles