【问题标题】:Angular services not being defined in beforeEach in KarmaKarma 的 beforeEach 中未定义 Angular 服务
【发布时间】:2023-03-11 21:41:01
【问题描述】:

我有一个使用 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

你们能帮帮我吗?

【问题讨论】:

    标签: angularjs jasmine karma-runner angular-mock


    【解决方案1】:

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

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

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

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

    karma.conf files 数组中缺少该 url。它正在生成错误:

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

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

    【讨论】:

      【解决方案2】:

      我记得两件事:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多