angularjs - 为 Karma 测试注入(inject)服务时未定义服务 - AngularJS

标签 angularjs testing gulp karma-jasmine

我在互联网上看到了一些这样的问题,但似乎没有一个答案能解决我的问题。我有一项服务在我提供的应用程序中完美运行,但当我在 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/

相关文章:

android - 单个设备上的多个 APK

asp.net - 从下拉列表更改登录用户以进行角色测试

node.js - 将 Gulp 任务组合成一个 gulp-rev list

angularjs - 如何禁用对 Ag-grid 中特定列的排序?

javascript - 如何使用 AngularJS 创建发布/订阅模式

javascript - 如何在 Angular 中访问动态添加的 DOM 元素?

angularjs - 为移动应用程序的 UI 小部件选择库

testing - 无法使用 Angular-cli 运行 Karma

javascript - 为什么我在创建带参数的任务时得到 "Task is not in your gulpfile"?

javascript - Gulp concat、uglify 处理 ES6 导出的库