如何使用 Webpack 和 Babel 从 Karma 的代码覆盖率中排除规范文件

How Can I Exclude Spec Files from Code Coverage with Karma using Webpack and Babel?

本文关键字:范文件 排除 文件 代码覆盖率 Webpack 何使用 Babel Karma      更新时间:2023-09-26

>问题

我正在开发一个配置了 webpackbabelkarma 的小型 react-redux 项目。我在 karma 中添加了代码覆盖率,但我找不到将测试文件排除在覆盖率之外的方法。所以我的代码覆盖率有spec文件。

如何将这些spec文件排除在覆盖范围之外?

我尝试使用正则表达式来排除spec文件,但由于它是由webpack加载的,因此它不起作用。

tests.webpack.js

const context = require.context('./src', true, /.+'Spec'.js$/);
context.keys().forEach(context);
module.exports = context;

webpack.config.js

module.exports = {
  entry: './src/index.js',
  output: {
    path: __dirname,
    filename: 'dist/bundle.js'
  },
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.js', '.scss'],
    modulesDirectories: [
      'node_modules',
      'src'
    ]
  },
  module: {
    preLoaders: [
      {
        test: /'.js$/,
        loader: 'eslint-loader',
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /'.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
    ],
  },
};

karma.config.js

var path = require('path');
module.exports = function (config) {
  config.set({
    browsers: ['PhantomJS'],
    singleRun: true,
    frameworks: ['mocha', 'sinon-chai'],
    files: [
      'tests.webpack.js'
    ],
    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap']
    },
    reporters: ['mocha', 'osx', 'coverage'],
    webpack: {
      module: {
        preLoaders: [
          {
            test: /'.js$/,
            exclude: [
              path.resolve('src/'),
              path.resolve('node_modules/')
            ],
            loader: 'babel'
          },
          {
            test: /'.js$/,
            include: path.resolve('src/'),
            loader: 'isparta'
          }
        ]
      }
    },
    webpackServer: {
      noInfo: true
    },
    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    }
  });
};

这就是我在项目中的做法,我的所有测试都位于每个组件包含__test__文件夹中。您应该能够将其更改为类似/'.spec.js$/的正则表达式。

karmaConfig.webpack.module.preLoaders = [{
  test    : /'.(js|jsx)$/,
  include : new RegExp(config.dir_client),
  loader  : 'isparta',
  exclude : [
    /node_modules/,
    /__test__/,
  ],
}];

在您的情况下,您需要将排除添加到配置的这一位中。

{
    test: /'.js$/,
    include: path.resolve('src/'),
    loader: 'isparta'
}

我通过在 .forEach(context) 之前放置一个 .filter() 来过滤掉我不想要的结果来解决这个问题。

const includes = require('lodash/includes');
const context = require.context('./src', true, /'.test'.js$/);
context.keys()
  .filter(file => includes(file, './api/') === false)
  .forEach(context);

您也可以将其直接写入 .forEach() 中。

const includes = require('lodash/includes');
const context = require.context('./src', true, /'.test'.js$/);
context.keys()
  .forEach(file => {
    if (includes(file, './api/') === false) {
      context(file);
    }
  });

如果您不使用 Lodash,您可以使用:

file.indexOf('./api/') === -1