istanbul-instrumenter-loader


Instrument JS文件与istanbul-lib-instrument 一起用于后续代码覆盖率报告。

安装

npm i -D istanbul-instrumenter-loader

用法

#

结构

├─ src
│ |– components
│ | |– bar
│ | │ |─ index.js
│ | |– foo/
│     |– index.js
|– test
| |– src
| | |– components
| | | |– foo
| | | | |– index.js

为生成所有组件(包括你没写测试的那些)的代码覆盖率报告,你需要 require 所有业务测试的代码。相关内容在 karma-webpack 其他用法中有涉及

test/index.js

// requires 所有在 `project/test/src/components/**/index.js` 中的测试
const tests = require.context('./src/components/', true, /index\.js$/);

tests.keys().forEach(tests);

// requires 所有在 `project/src/components/**/index.js` 中的组件
const components = require.context('../src/components/', true, /index\.js$/);

components.keys().forEach(components);

ℹ️  以下为 karma 的唯一入口起点文件

karma.conf.js

config.set({
  ...
  files: [    'test/index.js'
  ],
  preprocessors: {    'test/index.js': 'webpack'
  },
  webpack: {
    ...
    module: {
      rules: [        // 用 Istanbul 只监测业务代码
        {
          test: /\.js$/,
          use: { loader: 'istanbul-instrumenter-loader' },
          include: path.resolve('src/components/')
        }
      ]
    }
    ...
  },
  reporters: [ 'progress', 'coverage-istanbul' ],
  coverageIstanbulReporter: {
    reports: [ 'text-summary' ],
    fixWebpackSourcePaths: true
  }
  ...
});

使用 Babel

You must run the instrumentation as a post step

webpack.config.js

{
  test: /\.js$|\.jsx$/,
  use: {
    loader: 'istanbul-instrumenter-loader',
    options: { esModules: true }
  },
  enforce: 'post',
  exclude: /node_modules|\.spec\.js$/,
}

Options

此 loader 支持 istanbul-lib-instrument 的所有配置选项

NameTypeDefaultDescription
debug{Boolean}falseTurn on debugging mode
compact{Boolean}trueGenerate compact code
autoWrap{Boolean}falseSet to true to allow return statements outside of functions
esModules{Boolean}falseSet to true to instrument ES2015 Modules
coverageVariable{String}__coverage__Name of global coverage variable
preserveComments{Boolean}falsePreserve comments in output
produceSourceMap{Boolean}falseSet to true to produce a source map for the instrumented code
sourceMapUrlCallback{Function}nullA callback function that is called when a source map URL is found in the original code. This function is called with the source filename and the source map URL

webpack.config.js

{
  test: /\.js$/,
  use: {
    loader: 'istanbul-instrumenter-loader',
    options: {...options}
  }
}
-->