我建议你使用Karmajs
Karmajs 是一个测试运行器,因此您可以将其配置为使用 mocha 运行测试,也可以使用 webpack 预处理您的测试,因此所有预处理(对于 NormalModuleReplacementPlugin 和任何其他)都已完成当您使用 Karma 执行测试时,可以使用 via webpack 配置。
基本上,在您的应用程序中安装 Karma 及其相关软件包
yarn add karma karma-chai-plugins karma-chrome-launcher karma-cli karma-coverage karma-mocha karma-mocha-reporter karma-sinon-chai karma-sourcemap-loader karma-webpack
创建karma.conf.js
const webpackConfig = require('./webpack.config');
const webpack = require('webpack');
webpackConfig.devtool = 'inline-source-map';
webpackConfig.plugins = [
new webpack.ProvidePlugin({
'es6-promise': 'es6-promise',
}),
];
module.exports = function (config) {
config.set({
browsers: [ 'Chrome' ],
// karma only needs to know about the test bundle
files: [
'../node_modules/babel-polyfill/dist/polyfill.js',
'karma.globals.js',
'tests.bundle.js',
],
frameworks: [ 'chai', 'mocha' ],
// run the bundle through the webpack and sourcemap plugins
preprocessors: {
'tests.bundle.js': [ 'webpack', 'sourcemap' ],
},
// reporters: [ 'mocha', 'coverage' ],
reporters: [ 'mocha' ],
// coverageReporter: {
// type: 'text-summary',
// includeAllSources: true
// },
singleRun: false,
autoWatch: true,
// webpack config object
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
},
});
};
创建tests.bundle.js 为您的所有测试文件运行测试,在此示例中,我们所有的测试文件都有一个文件扩展名.spec.js 并位于./src 目录中。
tests.bundle.js
const context = require.context('./src', true, /\.spec\.js$/);
context.keys().forEach(context);
export default context;
要设置需要在所有应用/测试中可用的全局变量,可以使用karma.globals.js 文件进行设置。
karma.globals.js
const __DEV__ = false;
const INITIAL_STATE = {
name: 'My App',
version: 'v2.5.6'
};
以上配置完成后,您可以通过执行以下命令从创建 karma.config.js 和 package.json 的目录中运行所有测试。
yarn karma start
注意:测试也可以配置为在无头浏览器(如 phantomjs)中执行,在此示例中,我们使用 Chrome 浏览器运行测试。