我的代码依赖于大量其他代码,并且在从普通 index.html 文件运行时在浏览器中最后加载。当然,当依赖项 1 是 jquery,依赖项 2 使用 $.html(),并且我的代码第三次加载时,这在浏览器中工作得很好。
但是在 Karma 中,一切都停止了,因为我正在从凉亭加载“jquery”,而不是“$”。
需要明确的是:不是我的代码造成错误,而是依赖关系。我没有测试我的代码,因为在那之前一切都出错了。
那么如何让测试发挥作用呢?
注意:我也通过 webpack 运行所有东西,所以我可以使用 ES6 代码,但是 webpack 也是在 Karma 中加载的,所以应该没有效果。
Chrome 45.0.2454 (Mac OS X 10.11.0) ERROR
Uncaught TypeError: Cannot set property '$' of undefined
at /Users/tom/dev/orm/bower_components/jointjs/dist/joint.js:37
Webpack.conf.js:
var webpack = require('webpack');
module.exports = {
devtool: 'source-map-loader',
externals: [
'jquery',
'joint',
'backbone',
'loadash'
],
// entry: './src/index.js',
// output: {
// path: './public',
// filename: 'designer.js'
// },
plugins: [
new webpack.ProvidePlugin({'$': 'jquery', 'jointjs': 'joint'})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
Karma.conf.js:
// Karma configuration
// Generated on Thu Oct 08 2015 10:54:47 GMT+0200 (CEST)
var webconf = require('./webpack.config.js');
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: [
'jasmine',
'requirejs',
'bower'
],
// list of files / patterns to load in the browser
files: [
'test-main.js',
{
pattern: 'test/*.js',
included: false
}
],
bowerPackages: [
'jquery',
'jointjs',
'backbone',
'lodash'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/*.js': [
'webpack',
'sourcemap'
],
'src/**/*.js': [
'webpack',
'sourcemap'
]
},
webpack: webconf,
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: [
'progress'
],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [
'PhantomJS',
'Chrome'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};