覆盖报告与karma和javascript和typescript src文件的混合

Coverage reports with karma and a mix of javascript and typescript src files

本文关键字:src 文件 混合 typescript javascript 报告 karma 覆盖      更新时间:2023-09-26

我有一个项目,我使用webpack进行开发/测试,karma作为我的测试运行器。这个项目的源文件一半用js编写,一半用ts/tsx编写。测试套件完全是用js编写的。我目前使用的是karma-coverage,它显示了我所有js源文件的覆盖率报告,但它不支持typescript文件。我所有的测试都运行了,没有问题,我只是想要所有测试文件的覆盖率报告。有人能给我指个方向吗?

如果有帮助的话,这是我的karma.conf.js。

'use strict';
const webpackCfg = require('./webpack.config')('test');
module.exports = function karmaConfig(config) {
  config.set({
    browsers: ['Chrome'],
    files: [
      'test/loadtests.js'
    ],
    port: 8080,
    captureTimeout: 60000,
    frameworks: [
      'mocha',
      'chai',
      'sinon'
    ],
    client: {
      mocha: {}
    },
    singleRun: true,
    reporters: ['mocha', 'coverage', 'junit'],
    mochaReporter: {
      output: 'autowatch'
    },
    preprocessors: {
      'test/loadtests.js': ['webpack', 'sourcemap']
    },
    webpack: webpackCfg,
    webpackServer: {
      noInfo: true
    },
    junitReporter: {
      outputDir: 'coverage',
      outputFile: 'junit-result.xml',
      useBrowserName: false
    },
    coverageReporter: {
      dir: 'coverage/',
      watermarks: {
        statements: [70, 80],
        functions: [70, 80],
        branches: [70, 80],
        lines: [70, 80]
      },
      reporters: [
        { type: 'text' },
        {
          type: 'html',
          subdir: 'html'
        },
        {
          type: 'cobertura',
          subdir: 'cobertura'
        },
        {
          type: 'lcovonly',
          subdir: 'lcov'
        }
      ]
    }
  });
};

和我的webpack测试配置的相关部分

  {
      devtool: 'inline-source-map',
      externals: {
        cheerio: 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/addons': true,
        'react/lib/ReactContext': true,
      },
      module: {
        preLoaders: [
          {
            test: /'.(js|jsx)$/,
            loader: 'isparta-loader',
            include: [
              this.srcPathAbsolute
            ]
          }
        ],
        loaders: [
          {
            test: /'.cssmodule'.css$/,
            loaders: [
              'style',
              'css?modules&importLoaders=1&localIdentName=[name]-[local]-[hash:base64:5]'
            ]
          },
          {
            test: /^.((?!cssmodule).)*'.css$/,
            loader: 'null-loader'
          },
          {
            test: /'.(sass|scss|less|styl|png|jpg|gif|mp4|ogg|svg|woff|woff2)$/,
            loader: 'null-loader'
          },
          {
            test: /'.json$/,
            loader: 'json'
          },
          {
            test: /'.ts(x?)$/,
            exclude: /node_modules/,
            loader: ['babel', 'ts-loader']
          },
          {
            test: /'.(js|jsx)$/,
            loader: 'babel-loader',
            query: {
              presets: ['airbnb']
            },
            include: [].concat(
              this.includedPackages,
              [
                this.srcPathAbsolute,
                this.testPathAbsolute
              ]
            )
          }
        ]
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': '"test"'
        })
      ]
    }

经过几天的灵魂和谷歌搜索数百个浏览器选项卡,我找到了一个工作的解决方案。这里使用的是TypeScript 2。和Webpack 2.x。test.js是入口点。它也可以是test.ts(最终会是)。在那个入口点,我加载我的*.spec.js*.spec.ts文件。然后这些文件导入它们需要测试的源文件。我已经把所有的webpack配置在karma.conf.js,所以它更容易看到:

let myArgs = require('yargs').argv;
let path = require('path');
let webpack = require('webpack');
module.exports = function(config) {
  const REPORTS_PATH = myArgs.reportsPath ? myArgs.reportsPath :path.join(__dirname, 'build');
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'es6-shim'],
    files: [
      './test.js'
    ],
    exclude: [],
    reporters: ['progress', 'spec', 'coverage', 'junit', 'coverage-istanbul'],
    preprocessors: {
      './test.js': ['webpack', 'sourcemap']
    },
    webpackServer: {
       noInfo: true // prevent console spamming when running in Karma!
    },
    webpack: {
      devtool: 'inline-source-map',
      resolve: {
        modules: [
          path.resolve('./node_modules'),
          path.resolve('./')
        ],
        extensions: ['.js', '.ts', '.css', '.scss']
      },
      plugins: [
        new webpack.ProvidePlugin({
           $: "jquery",
           jQuery: "jquery",
          "window.jQuery": "jquery"
        })
      ],
      module: {
        rules: [
          {
            enforce: 'pre',
            test: /'.js$/,
            use: 'source-map-loader',
            exclude: [/node_modules/]
          },
          {
            test: /'.ts$/,
            use: [{
              loader: 'awesome-typescript-loader',
              options: {
                module: 'commonjs'
              },
            }]
          },
          {
            test: /'.js$/,
            use: [{
            loader: 'awesome-typescript-loader',
              options: {
                entryFileIsJs: true,
                transpileOnly: true
              }
            }],
            exclude: [/node_modules/],
          },
          {
            enforce: 'post',
            test: /'.(js|ts)$/,
            use: [{
              loader: 'istanbul-instrumenter-loader',
              options: {
                esModules: true
              }
            }],
            exclude: [/node_modules/, /'.spec'.(js|ts)$/, /test/]
          },
          { test: /'.html/, use: 'raw-loader' },
          { test: /'.(s)?css$/, use: 'null-loader' },
          { test: /'.(png|jpg|jpeg|gif|svg|pdf)$/, use: 'null-loader' },
          { test: /'.woff(2)?('?v=[0-9]'.[0-9]'.[0-9])?$/, use: 'null-loader' },
          { test: /'.(ttf|eot)('?v=[0-9]'.[0-9]'.[0-9])?$/, use: 'null-loader' },
          { test: /'.json$/, use: 'null-loader' }
        ]
      }
    },
    coverageReporter: {
      type: 'in-memory'
    },
    coverageIstanbulReporter: {
      //TODO: Figure out why the 'html' reporter blows up with istanbul-reports (something with absolute path copying files)
      reports: ['text-summary', 'cobertura'],
      // base output directory
      dir: REPORTS_PATH,
      fixWebpackSourcePaths: true,
      'report-config': {
        cobertura: {
          file: 'coverage.xml'
        },
        'text-summary': {
          file: null
        }
      }
    },
    junitReporter: {
      outputDir: `${REPORTS_PATH}/junit/`,
      outputFile: 'jasmine-results.xml'
    },
    // Hide webpack build information from output
    webpackMiddleware: {
      stats: {
        chunkModules: false,
        colors: true
      },
      noInfo: 'errors-only'
    },
    colors: true,
    logLevel: config.LOG_ERROR,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    autoWatchBatchDelay: 400
  });
};

所以,这里的关键部分是awesome-typescript-loader, karma-coverage-istanbul-reporter, source-map-loader,在tsconfig.json中,你想在compilerOptions中设置它们:

"inlineSourceMap": true,
"sourceMap": false,

我指出了html报告的TODO。它确实工作,但我无法让它输出到一个自定义目录(subdir)与TypeScript文件作为它的一部分。JavaScript只能正常工作。可能是istanbul-reports特定于windows的问题。如果您将html添加到coverageIstanbulReporter下的reports数组中,您应该在项目目录中看到它,但将其放在REPORTS_PATH中可能会遇到问题。

同样值得注意的是,我使用karma-remap-coverage而不是karma-coverage-istanbul-reporter有很多运气,但前者不会正确生成覆盖的cobertura报告,这是我需要的Jenkins