javascript - 调用 karma 测试时未定义 Angular 错误

标签 javascript angularjs karma-jasmine

我确定这与 angular-mock.js 有关,但我不知道我需要做什么,因为一切似乎都很好。我只是使用 angular-seed 应用程序的默认设置。 请帮忙解决问题

karma.conf.js

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

    basePath : '../',

    files : [
      'bower_components/angular/angular.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  });
};

controllers.js

'use strict';
/* Controllers */

var app = angular.module('myApp.controllers', []);
app.constant('RESTURL', 'http://'+ location.hostname + ':8003');

app.controller('MainCtrl', ['$scope', 'dataService', 'flash', 'mySharedService','facetSearchService', 'facetSelectionService', 'RESTURL',  function($scope, dataService, flash, sharedService, facetSearch, facet, RESTURL) {
      $scope.RESTURL =  RESTURL;
      $scope.loading = true;
      $scope.data = null;
      $scope.resultCount = 0;
      $scope.currentPage = 0;
      $scope.pageSize = 10;

          ....
])}

controllerSpec.js

'use strict';

/* jasmine specs for controllers go here */

describe('controllers', function(){
  beforeEach(module('myApp.controllers'));


  it('should test MainCtrl', inject(function($controller) {
    //spec body
    var scope = {},
    ctrl = $controller('MainCtrl', {$scope:scope});

    expect($scope.RESTURL).toBe('http://'+ location.hostname + ':8003'));
  }));


});

项目文件结构: enter image description here

最佳答案

我相信你运行了“bower install”来安装依赖项?

bower_components 的路径不正确。 “../”的基本路径将使 karma 看起来在您项目的根目录中,但您的 bower_components 位于您的“app”文件夹中。 karma.conf 中的"file"需要以“app”为前缀。

关于javascript - 调用 karma 测试时未定义 Angular 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23574706/

相关文章:

javascript - 使用 jQuery 滚动 div

javascript - 为什么在使用 for 循环添加事件监听器时会出现 TypeError?

javascript - 'next_level_button' 与属性 android :layout_below (attr) reference 不兼容

javascript - 在 ng-if ng-switch 语句中单击后如何禁用 ng-click?

javascript - 如何从 AngularJS Controller 设置值

javascript - Jasmine 不注入(inject)服务

javascript - 如何让 Karma html 记者在 karma conf 中工作?

javascript - 使用 CTR 模式对 crypto-js 进行加密并在 Node crypto 上进行解密问题

jquery - 使用 jQuery 访问动态添加的 DOM 元素内的 Angular 数据绑定(bind)

angular - 如何对 IntervalObservable 进行单元测试