角度服务没有在Karma中的beforeEach中定义

时间:2016-04-04 20:23:12

标签: angularjs jasmine karma-runner angular-mock

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

这是我的测试类:

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 方法中调用注入函数,但我不确定。我在测试中得到了未定义,好像变量从未得到任何值。

 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

你们能帮助我吗?

2 个答案:

答案 0 :(得分:1)

我记得两件事:

  • 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'
],

答案 1 :(得分:1)

最后它只是一个愚蠢的错误(因为大多数都是)。

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

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

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

karma.conf 文件数组中缺少该网址。它产生了一个错误:

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,文件运行良好。这是误导性错误消息的另一种情况。