我在互联网上看到了一些这样的问题,但似乎没有一个答案能解决我的问题。我有一项服务在我提供的应用程序中完美运行,但当我在 Karma 中测试它时,它没有被定义。
我在 src
文件夹中有我的模块和关联的 Controller 、指令和服务。该文件的结构如下:
angular.module('cst-error-framework', ['md.alerts', 'md.input', 'md.modals']);
angular.module('md.alerts', [])
.directive(//..associated directives here
angular.module('md.input', [])
//blah blah blah
angular.module('md.modals', [])
//directives and controllers
.factory('mdErrorHandler', function () {
//contents here
});
我知道这看起来有点麻烦,但还有其他原因我将它放在一个文件中。
然后我的 mdErrorHandler
规范如下:
describe('Service errorHandler', function () {
beforeEach(function() {
module('cst-error-framework');
angular.mock.module('templates');
});
var mdErrorHandler;
beforeEach(inject(function(_mdErrorHandler_){
mdErrorHandler = _mdErrorHandler_;
console.log(mdErrorHandler);
}));
这是我的karma.conf.js
:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-mocks/angular-mocks.js',
'dist/cst-error-framework.js',
'dist/cst-error-framework.css',
'src/**/templates/*.html',
'src/helpers/*.js',
'src/**/test/*.spec.js'
],
preprocessors : {
'src/**/templates/*.html': 'ng-html2js'
},
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'templates'
},
exclude: [],
port: 9876,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
singleRun: false
});
'use strict';
};
然后当我运行 karma 测试时,我的 mdErrorHandler
没有被定义,所以我的 console.log
的结果只是 []
.
知道发生了什么事吗?这与 Karma 加载东西的顺序有关吗?想避免必须完全重构我的主要 .js
文件。
编辑 开始怀疑可能是我的 gulpfile 中的某些内容导致了问题?这是我的 Karma Gulp 任务:
gulp.task('karma', ['build'], function(done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
最佳答案
在测试中实例化模块时,不需要函数声明。
所以代替
beforeEach(function() {
module('cst-error-framework');
angular.mock.module('templates');
});
尝试
beforeEach(module('cst-error-framework');
beforeEach(angular.mock.module('templates');
关于angularjs - 为 Karma 测试注入(inject)服务时未定义服务 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230548/