简体   繁体   English

Angular-cli 测试覆盖所有文件

[英]Angular-cli test coverage all files

I am running the following command to unit test and generate code code coverage report.我正在运行以下命令进行单元测试并生成代码代码覆盖率报告。

ng test --code-coverage

It is writing code coverage report in coverage folder.它正在覆盖文件夹中编写代码覆盖率报告。

I need to see the coverage of the whole project and not just the file for which there are tests.我需要查看整个项目的覆盖率,而不仅仅是有测试的文件。

karma.conf.js业力配置文件

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma'),
      require('karma-coverage'),
      require('karma-sourcemap-loader')

    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
        reports: {
          html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress', 'kjhtml'],
    coverageReporter: {
      includeAllSources: true
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

I had the same issue and I found a simple workaround that does the trick for me without any big configuration.我遇到了同样的问题,我找到了一个简单的解决方法,无需任何大配置即可为我解决问题。

  1. In your app folder, create a file app.module.spec.ts在您的 app 文件夹中,创建一个文件 app.module.spec.ts
  2. In this file add an import to your app module.在此文件中,向您的应用模块添加导入。

import './app.module';

That's it ;)就是这样 ;)

The point is, your app module is most likely the central part of your application which imports any other used files directly or indirectly.关键是,您的应用程序模块很可能是您的应用程序的核心部分,它直接或间接地导入任何其他使用过的文件。 Now that you have created the spec file, everything that is included by your module should also be included in the test coverage report.现在您已经创建了规范文件,模块包含的所有内容也应该包含在测试覆盖率报告中。

I am not 100% sure if this works with lazy loaded modules.我不是 100% 确定这是否适用于延迟加载的模块。 If not, you can simply import those lazy loaded modules in your app.module.spec.ts as well, or create a spec file per module, where you import the module.如果没有,您也可以简单地在 app.module.spec.ts 中导入那些延迟加载的模块,或者为每个模块创建一个规范文件,在其中导入模块。

Here is the way to do this:这是执行此操作的方法:

  1. Add client section to your karma.conf.js like this:client部分添加到您的karma.conf.js如下所示:

     plugins: [ ... ], client: { codeCoverage: config.angularCli.codeCoverage }, files: [ ... ],
  2. Change your test.ts to require files according to codeCoverage parameter:更改test.ts根据需要文件codeCoverage参数:

     let context; if (__karma__.config.codeCoverage) { context = require.context('./app/', true, /\\.ts/); } else { context = require.context('./app/', true, /\\.spec\\.ts/); } context.keys().map(context);

UPDATE:更新:

Since Angular CLI 1.5.0 additional steps are required:由于 Angular CLI 1.5.0需要额外的步骤:

  1. Next to tsconfig.spec.json add tsconfig-cc.spec.json file with the following content:tsconfig.spec.json添加tsconfig-cc.spec.json文件,内容如下:

     { "extends": "./tsconfig.spec.json", "include": [ "**/*.ts" ] }
  2. In your angular-cli.json add the following to apps array:在您的angular-cli.json将以下内容添加到apps数组:

     { "root": "src/", "polyfills": "polyfills.ts", "test": "test.ts", "testTsconfig": "tsconfig-cc.spec.json" }
  3. In your karma.conf.js add the following to angularCli section:在您的karma.conf.js将以下内容添加到angularCli部分:

     app: config.angularCli.codeCoverage ? '1' : '0'

    eventually it should look something like this:最终它应该是这样的:

     angularCli: { environment: 'dev', app: config.angularCli.codeCoverage ? '1' : '0' },

So what's happening here?那么这里发生了什么?

Apparently they have fixed Angular compiler plugin and it takes the file globs from tsconfig.spec.json now.显然他们已经修复了 Angular 编译器插件,它现在从tsconfig.spec.json获取文件 globs。 As long as we include only **/*.spec.ts in tsconfig.spec.json these are the only files that will be included in coverage.只要我们在tsconfig.spec.json中只包含**/*.spec.ts ,这些是唯一包含在覆盖范围内的文件。

The obvious solution is making tsconfig.spec.json include all the files (in addition to require.context ).显而易见的解决方案是使tsconfig.spec.json包含所有文件(除了require.context )。 However, this will slow down all the tests even when running without coverage (which we don't want to).但是,即使在没有覆盖的情况下运行(我们不想这样做),这也会减慢所有测试的速度。

One of the solutions is using the ability of angular-cli to work with multiple apps.解决方案之一是使用angular-cli来处理多个应用程序。
By adding another entry into apps array, we're adding another configuration for "another" (which is actually the same one) app.通过在apps数组中添加另一个条目,我们为“另一个”(实际上是同一个)应用程序添加了另一个配置。
We strip out all the irrelevant information in this config, leaving just the test configuration, and put another tsconfig which includes all the ts files.我们tsconfig这个配置中所有不相关的信息,只留下测试配置,并放置另一个包含所有ts文件的tsconfig
Finally, we're telling angular-cli karma plugin to run the tests with the configuration of the second app (index 1 ) in case it is running with code coverage and run with the configuration of the first app (index 0 ) if it is running without code coverage.最后,我们告诉angular-cli karma插件使用第二个应用程序(索引1 )的配置运行测试,以防它以代码覆盖率运行,并使用第一个应用程序(索引0 )的配置运行(如果是)在没有代码覆盖的情况下运行。

Important note: in this configuration I assume you have only one application in .angular-cli.json .重要提示:在此配置中,我假设您在.angular-cli.json只有一个应用程序。 In case you have more you have to adjust indexes accordingly.如果您有更多,则必须相应地调整索引。

I've just created karma plugin, which adds all the files in the project to coverage statistic - https://github.com/kopach/karma-sabarivka-reporter .我刚刚创建了 karma 插件,它将项目中的所有文件添加到覆盖率统计中 - https://github.com/kopach/karma-sabarivka-reporter

To use it → install npm install --save-dev karma-sabarivka-reporter使用它 → 安装npm install --save-dev karma-sabarivka-reporter

And update karma.conf.js like this:并像这样更新karma.conf.js

reporters: [
  // ...
  'sabarivka'
  // ...
],
coverageReporter: {
    include: 'src/**/!(*.spec|*.module|environment*).ts', // glob patter which  matchs all the files you want to be included into the coverage result
    exclude: 'src/main.ts',
    // ...
},

This solves issue without any other manipulation.这解决了没有任何其他操作的问题。 Easy to add to existing projects as well as to new ones.易于添加到现有项目以及新项目中。

1) in ./src/test.ts set / Then we find all the tests. 1)在./src/test.ts中设置/然后我们找到所有的测试。

const context = require.context(‘./app/’, true, /\.ts/);

instead of standart 2) update src/tsconfig.spec.json with而不是标准 2) 更新 src/tsconfig.spec.json

“include”: [


 “**/*.ts”

3) in angular.json set 3) 在 angular.json 中设置

“test”: {
     “builder”: “@angular-devkit/build-angular:karma”,
     “options”: {
       “codeCoverage”: true,
       “main”: “src/test.ts”,
       “polyfills”: “src/polyfills.ts”,
       “tsConfig”: “src/tsconfig.spec.json”,
       “karmaConfig”: “src/karma.conf.js”,
       “styles”: [
         “src/styles.scss”
       ],
       “scripts”: [],
       “assets”: [
         “src/favicon.ico”,
         “src/assets”,
         “src/config”,
         “src/manifest.json”
       ]
     }
   }

I mean add this param “codeCoverage”: true我的意思是添加这个参数“codeCoverage”:true

And for me it includes all files对我来说它包括所有文件

I mean add this param “codeCoverage”: true我的意思是添加这个参数“codeCoverage”:true

And for me it includes all files对我来说它包括所有文件

karma.conf.js should be like this. karma.conf.js 应该是这样的。 No other configuration is required ng cli will take care of everything.不需要其他配置 ng cli 会处理一切。 stop the previous run ng test and run ng test --code-coverage .停止之前的运行ng test并运行ng test --code-coverage

module.exports = function (config) {
  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
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

使用下面给定的命令来检查代码覆盖率:

ng test -cc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM