我无法提供一个单一的 karma/webpack 配置的解决方案,我的解决办法是有两个 karma 配置文件 - 目前我对此感到非常满意。(我还有其他非 karma 的测试运行设置。)
一个配置文件在后台运行测试并提供准确的栈跟踪信息,用于我的 es6 代码;另一个使用 isparta-loader 进行覆盖率测试,以转译和插桩我的源代码。(isparta-loader 使用 isparta,它使用 istanbul)
因此,我的“运行测试”karma配置文件看起来有点像这样:
var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ],
singleRun: false,
frameworks: [ 'mocha' ], // Use the mocha test framework
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: [ 'mocha' ],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
// Use imports loader to hack webpacking sinon.
// https://github.com/webpack/webpack/issues/177
{
test: /sinon\.js/,
loader: "imports?define=>false,require=>false"
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: ['es2015'] }
}
]
}
},
webpackServer: {
noInfo: true
}
});
}
我的覆盖率Karma配置看起来有点像这样:
var webpack = require('webpack'),
path = require('path');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ],
singleRun: true,
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack' ]
},
reporters: [ 'coverage' ],
webpack: {
// *optional* babel options: isparta will use it as well as babel-loader
babel: {
presets: ['es2015']
},
// *optional* isparta options: istanbul behind isparta will use it
isparta: {
embedSource: true,
noAutoWrap: true,
// these babel options will be passed only to isparta and not to babel-loader
babel: {
presets: ['es2015']
}
},
module: {
loaders: [
{
test: /sinon\.js/,
loader: "imports?define=>false,require=>false"
},
// Perform babel transpiling on all non-source, test files.
{
test: /\.js$/,
exclude: [
path.resolve('node_modules/'),
path.resolve('lib/')
],
loader: 'babel-loader',
query: { presets: ['es2015'] }
},
// Instrument source files with isparta-loader (will perform babel transpiling).
{
test: /\.js$/,
include: [
path.resolve('lib/')
],
loader: 'isparta'
}
]
}
},
webpackServer: {
noInfo: true
},
coverageReporter: {
reporters: [
{ type: 'html', dir: 'coverage/' },
{ type: 'text' }
]
}
});
}
这个第二个配置提供了一个文本报告,在终端上可以立即看到覆盖率概要,还有一个HTML报告,可以很好地突出未经测试的代码。对于sinon进行了一些hack处理,但与此问题无关。 tests.webpack.js
使用webpack的require.context
来引入我用mocha编写的浏览器测试。还需要各种karma-*插件。