Angular 服务未在 Karma 的 beforeEach 中定义

Angular services not being defined in beforeEach in Karma

我有一个 Angular 应用程序使用 Jasmine 和 Karma 进行测试。

这是我的测试class:

var data = require('./user.mock.js');

describe('Service: UserService', function () {
  var ServerUrl;
  var httpBackend;
  var userService;

  beforeEach(angular.mock.module('myModule'));

  beforeEach(angular.mock.inject(function (_userService_, $httpBackend, _ServerUrl_) {
    userService = _userService_;
    httpBackend = $httpBackend;
    ServerUrl = _ServerUrl_;
  }));

  describe('when get the active users from backend', function () {
    // given
    beforeEach(function () {
      httpBackend
        .whenGET(ServerUrl + '/users')
        .respond(angular.copy(data.activeUsers));
    });

    it('should return the list of active users', function () {
      var expectedUsers = angular.copy(data.activeUsers);
      expectedUsers[0].profilePicture = ServerUrl + '/pictures/' + expectedUsers[0].id + '/small/show';
      expectedUsers[1].profilePicture = ServerUrl + '/pictures/' + expectedUsers[1].id + '/small/show';

      userService
        .listUsers()
        .then(function(users) {
          expect(users).toEqual(expectedUsers);
        });

      httpBackend.flush();
    });
  });

这是我的业力会议:

// Karma configuration
// Generated on Tue May 19 2015 15:02:17 GMT+0100 (WEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: [ 'jasmine', 'browserify'],

    // list of files / patterns to load in the browser
    files: [
      'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
      // bower:js
      "bower_components/jquery/dist/jquery.js",
      "bower_components/angular/angular.js",
      "bower_components/angular-mocks/angular-mocks.js",
      "bower_components/angular-animate/angular-animate.js",
      "bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
      "bower_components/angular-cookies/angular-cookies.js",
      "bower_components/angular-gettext/dist/angular-gettext.js",
      "bower_components/angular-http-auth/src/http-auth-interceptor.js",
      "bower_components/angular-notify/dist/angular-notify.js",
      "bower_components/angular-resource/angular-resource.js",
      "bower_components/angular-route/angular-route.js",
      "bower_components/angular-sanitize/angular-sanitize.js",
      "bower_components/angular-touch/angular-touch.js",
      "bower_components/angular-ui-utils/ui-utils.js",
      "bower_components/angular-ui-map/ui-map.js",
      "bower_components/bootstrap-sass/assets/javascripts/bootstrap.js",
      "bower_components/bootstrap-select/dist/js/bootstrap-select.js",
      "bower_components/event-signal/dist/event-signal.min.js",
      "bower_components/google-map-infobubble/src/infobubble.js",
      "bower_components/moment/moment.js",
      "bower_components/ng-file-upload/ng-file-upload.js",
      "bower_components/ng-file-upload-shim/ng-file-upload-shim.js",
      "bower_components/angularUtils-pagination/dirPagination.js",
      // endbower
      'src/app/**/*.js',
      'src/app/views/**/*.html',
      'src/test/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.html': ['ng-html2js'],
      'src/**/*.js': ['browserify']
    },


    ngHtml2JsPreprocessor: {
      // strip this from the file path
      stripPrefix: 'src/',
      // prepend this to the


      // setting this option will create only a single module that contains templates
      // from all the files, so you can load them all with module('foo')
      moduleName: 'templatesForTest'
    },
    //
    // // test results reporter to use
    // // possible values: 'dots', 'progress', 'spec'
    // // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    // reporters: ['spec'],
    //
    //
    // // 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'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

当我从命令行 运行 karma test 时,注入的服务无法识别。我怀疑 beforeEach 方法中没有调用 inject 函数,但我不确定。我在测试中变得未定义,好像变量从未获得任何值。

 workFn@/Users/brunosiqueira/WebstormProjects/copcast-admin/bower_components/angular-mocks/angular-mocks.js:2507:60
    TypeError: undefined is not an object (evaluating 'httpBackend
            .whenGET') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 5994)
    /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:5994:18
    TypeError: undefined is not an object (evaluating 'userService
            .getUserVideos') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 6012)
    /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:6012:18

你们能帮帮我吗?

我记得两件事:

  • 配置文件中 JS 文件的顺序必须正确
  • 用法好像很对,就是这个。只需检查这是否使 差异:

    beforeEach(inject(function($controller, $rootScope, _myService_){ scope = $rootScope.$new(); myServiceSvc = _myService_; firstCtrl = $controller("firstCtrl",{ $scope: scope, myService: myServiceSvc }); }));

karma.conf

files: [
  'index.html',
  'lib/angular.min.js',
  'lib/angular-ui-router.min.js',
  'lib/angular-mocks/angular-mocks.js',
  'lib/app.js',      
  'tests/controller/basics.js'
],

最后这只是一个愚蠢的错误(大多数都是这样)。

使用 git bisect,我能够找到测试停止工作的提交。

在那次提交中,我看到我向项目添加了 ng-jwplayer 依赖项。该库需要在 html 文件之前进行 javascript 调用。

  'https://content.jwplatform.com/libraries/XXXXXX.js',

url 在 karma.conf files 数组中丢失。它正在生成一个错误:

files: [
  'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
  'https://content.jwplatform.com/libraries/XXXXXX.js',
  // bower:js
  'bower_components/jquery/dist/jquery.js',
  'bower_components/angular/angular.js',
  'bower_components/angular-animate/angular-animate.js',
  'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
  'bower_components/angular-cookies/angular-cookies.js',
  'bower_components/angular-gettext/dist/angular-gettext.js',
  'bower_components/angular-http-auth/src/http-auth-interceptor.js',
  'bower_components/angular-notify/dist/angular-notify.js',
  'bower_components/angular-resource/angular-resource.js',
  'bower_components/angular-route/angular-route.js',
  'bower_components/angular-sanitize/angular-sanitize.js',
  'bower_components/angular-touch/angular-touch.js',
  'bower_components/angular-mocks/angular-mocks.js',
  'bower_components/angular-ui-utils/ui-utils.js',
  'bower_components/angular-ui-map/ui-map.js',
  'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
  'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
  'bower_components/event-signal/dist/event-signal.min.js',
  'bower_components/google-map-infobubble/src/infobubble.js',
  'bower_components/moment/moment.js',
  'bower_components/ng-jwplayer/jwplayer.min.js',
  'bower_components/ng-file-upload/ng-file-upload.js',
  'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
  'bower_components/angularUtils-pagination/dirPagination.js',
  // endbower
  'src/app/**/*.js',
  'src/app/views/**/*.html',
  'src/test/**/*.js'
],

包含 url 后,文件运行良好。这是另一个误导性错误消息的例子。