Angular4 how to enable test coverage
Asked Answered
L

4

6

I am working on an Angular4 project.

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

I read every possible page I could find, but I am lost.

How do I set up code coverage in Angular4?

UPDATE2: I have now decided to use karma coverage reporter https://www.npmjs.com/package/karma-coverage and therefore reworked the karma conf file as per the description.

The package json got updated to.

I now see the folder being generated, but the HTML file shows an empty table, enter image description here

The test is being run and passes:

enter image description here not sure what to do from here.

Here is my package json.

   {
  "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"
  }
}

Followed by 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
        )
    ]
}

Followed by the now updated karma conf file:

  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

Lemnos answered 15/5, 2017 at 23:32 Comment(0)
W
2

I have researched through various articles and the easiest way i found was:-

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

  2. $ ng test --code-coverage

  3. Make sure you have http-server installed (npm install http-server -g) and then $ http-server -c-1 -o -p 9875 ./coverage

Open it in a chrome browser only.

Westerman answered 22/11, 2017 at 11:58 Comment(0)
R
1

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

If you want to inspect how it was configured, generate a project with the angular-cli and execute on the root folder ng eject, that will allow you to see the webpack configuration file.

Realtor answered 16/5, 2017 at 0:54 Comment(1)
I well and truly have given up on this story. I am now using Angular CLI, it makes working with Angular2 a thousand times easier.Lemnos
B
0

I had a similar issue trying to get angular4 cli to work in an setup after ng eject. It turned out to be a few simple lines for me in the package.json and the karma.conf.js

maybe this will help someone else doing it from scratch or from the ng eject point of view.

I added a coverage script to the package.json

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

Then for the karma config I had to add a line for the client.args and set the angularCli.codeCoverage to a variable isCoverage I create to read the command line option from the 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
  });

};
Babineaux answered 18/9, 2017 at 21:15 Comment(0)
C
0

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

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

codeCoverage is the important part if you want to run codeCoverage for an ejected app with the script command npm run test

Churlish answered 15/11, 2017 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.